Learning Lua

Learning Lua

Table of Contents

  • Background
  • Tables
    • metatable
  • functions
  • coroutine
  • Lua as Object-oriented programming


1 Background

Lua as an embedded language was popular in the game industry and also in any embedded scenario. I tried to wrote a Lua module for Nginx, which already has a ported Lua environment inside. And since this is my first time to get familiar with Lua, and to enjoy its simplicity.
My learning materials were no special, but its official document.

I wrote my notes down in order for future review.

2 Tables

To understand table is to understand Lua, or in another word, Lua's syntax was nothing but just tables, no more.
Tables in Lua is in similar with the dictionary in Python, in my view.

a = {}
a.x = 1
a['x'] = 1

2.1 metatable

Lua's metatable is similar to magic methods in python.

3 functions

Lua as a functional programming language, because the function is also the first-class variable. That's where the magic happened.

function rename(arg)
   return os.rename(arg.old, arg.new)
end

rename{old="older.txt", new="new.txt"}

4 coroutine

a coroutine is similar to the thread in another language.

co = coroutine.create(function(a, b)
      while true do
         coroutine.yield(a+b, a-b)
      end
end)

print(coroutine.status(co))
print(coroutine.resume(co, 20, 10))
print(coroutine.status(co))

5 Lua as Object-oriented programming

Lua implements inheritance and multi-inheritance by metatable.

-- single inheritance
Window = {}
Window.prototype = {x=0, y=0, width=100, height=100}
Window.mt = {}

function Window.new(o)
   setmetatable(o, Window.mt)
   return o
end

Window.mt.__index = function(table, key)
   return Window.prototype[key]
end

w = Window.new{x=10, y=20}

print(w.x)
print(w.width)


-- use createClass to generate class from multi-ones
function createClass(list)
   local c = {}

   local function search(k)
      for i=1, table.getn(list) do
         local v = list[i][k]
         if v then return v end
      end
   end

   -- class will search for each method in the list of its
   setmetatable(c, {__index = function(t, k)
                       local v = search(k)
                       t[k] = v
                       return v
   end})

   -- prepare c to be the metatable of its instances
   c.__index = c


   -- define a new constructor for this new class
   function c:new (o)
      o = o or {}
      setmetatable(o, c)
      return o
   end

   return c
end

Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp