More Table functions

From GMod Wiki

Jump to: navigation, search

Here is a list of more things you can do with tables, For more details look at the page matching to the function used.


About tables

Functions in tables

Tables are very flexible in Lua. You can basically have a table of ANYTHING. Even functions! Look at this example to see what I mean:

local supertable = {}
supertable.printtwice = function( str ) Msg( str .. "\n" .. str ) end
supertable.multrandom = function( numb ) return numb * math.Random( 0, 1 ) end
supertable.theanswer = 42
 
supertable.printtwice( tostring( supertable.multrandom( supertable.theanswer ) ) )

This would randomly multiply the number 42 and print it twice. Handy isn't it?

For loops with tables

But wait, there's more! They can also be sequential for use in for loops!

local functable = {}
functable[1] = function() Msg( "This is function one.\n" ) end
functable[2] = function() Msg( "Aaaand.... this is number 2.\n" ) end
functable[3] = function() Msg( "Ofcourse, it would be logical that this one is the third one.\n" ) end
functable[4] = function() ErrorNoHalt( "Looks like something went wrong here.\n" ) end
 
table.insert( functable, function() Msg( "The fifth one was added using table.insert.\n" ) end )
 
for i = 1, #functable do
    functable[i]()
end
 
Msg( "\n------------\n" )
 
table.sort( functable, function(a, b) return math.Rand( 0, 1 ) > 0.5 end )
table.insert( functable, 1, function() Msg( "Oh no, my whole table, RUINED!\n" ) end )
 
for i = 1, #functable do
    functable[i]()
end

Go back to main article

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox