Lua Programming Language

Index

If you notice any mistakes or have additions, click here.

Lua Code Snippets


-- Mnemonic to avoid confusing pairs()/ipairs(). 
KEYS = pairs
KEYS_VALS = pairs

-- Looping: iterate over all keys/values of table t 
for k,v in KEYS_VALS(t) do body end

-- Looping: print all keys of table 
for k in KEYS(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
        local 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 KEYS_VALS(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, Tutorials, FAQ

home
© 2010 Jim Brooks
Last modified: Tue Apr 13 10:20:16 CDT 2010