Lua Programming Language

Index

Please click here if you notice any mistakes or have additions.

Lua Code Snippets



-- Looping: iterate over all key/value pairs of table t 
for k,v in pairs(t) do body end

-- Looping: print all keys of table 
for k in pairs(t) do end

-- Looping: iterate by ordinals of a table 
for i=1, #t do end

-- To separate/split the words of a string: 
function SplitFields( str, sep )
    if ( str[string.len(str)] ~= sep ) then
        str2 = string.format( "%s%s", str, sep )
        return {str2:match((str2:gsub("[^"..sep.."]*"..sep, "([^"..sep.."]*)"..sep)))}
    else
        return {str:match((str:gsub("[^"..sep.."]*"..sep, "([^"..sep.."]*)"..sep)))}
    end
end

fields = SplitFields( str, "," )
for key,word in pairs(fields) do
    print( word )
end

Chaining Constructors Across Derivative Classes

This is an example of building a class hierarchy in Lua. Unlike C++, chaining constructor functions has to be done explictly.



-- Produces a metatable (class table) that inherits methods from another one. 
function lib.DerivesFrom( BaseMT, t )
    local t = t or {}
    setmetatable( t, BaseMT )
    BaseMT.__index = BaseMT
    return t
end

-- Produces an "instance table" from a "class table" (metatable). 
-- For use in a Class:new() method. 
function lib.NewInstance( classTable, argTable )
    -- Construct instance table. 
    local instance = argTable or {}
    setmetatable( instance, classTable )
    classTable.__index = classTable
    return instance
end

Base = { }  -- ONLY THE ROOT BASE CLASS CAN BEGIN WITH AN EMPTY TABLE 

-- ctor. 
function Base:new( name )
    -- If base class is being instantiated, the base class will be passed as self. 
    -- Or, the derivative is being instantiated, which chains ctors by passing its instance as self. 
    if ( self == Base ) then
        self = lib.NewInstance( Base )  -- not chained, need new instance 
    end

    self.name = name

    return self
end

-- lib.DerivedClass() produces a "class table" that inherits from another "class table". 
-- Derived becomes a metatable, inheriting from Base, from which instance tables can be produced. 
Derived = lib.DerivesFrom( Base )

function Derived:new( name, value )
    -- Make instance table from derived metatable. 
    if ( self == Derived ) then
        self = lib.NewInstance( Derived )
    end

    Base.new( self, name )  -- chain to parent's ctor 

    self.value = value  -- derivative-specific 

    return self
end

Lua Tools

  • Lua documentation generator
  • Lua JIT compiler

home
© 2009 Jim Brooks
Last modified: Mon Oct 20 09:20:55 EDT 2008