Introduction To The LUA Metatables: Default values in the declaration
21st September, 2011
Scripting, Tutorials
This tutorial is a small extension to the previous tutorial about Lua metatables. It show you another way to declare a metatable, how to add default values in your metatable.
The previous tutorial was about how to build an URL with post parameters using a metatable. It can be read here.
Warning: This tutorial is only viable for games using the Lua script, it doesn’t work for games exported in native code, because it uses LUA elements
Introduction
You can add default values in a metatable when declaring it.
The syntax is this one:
local myMetatable = {"value0", 32, hObject}
All the elements between the { } are the value, and the key is set automatically using an index, starting at 0.
Here, myMetatable[0] is “value0″, myMetatable[1] is 32 and myMetatable[2] is hObject
It’s exactly the same result than the code was:
local myMetatable = {} myMetatable[0] = "value0" myMetatable[1] = 32 myMetatable[2] = hObject
Sample
Below, you can find a small function using this kind of declaration:
-------------------------------------------------------------------------------- function MyGame.getMonthName ( nMonth ) -------------------------------------------------------------------------------- local month_of_year = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} return month_of_year[nMonth] -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
Call it with a month index, and you’ll get the month name.
Leave a Reply



(6 votes, average: 3.67 out of 5)


