Introduction to the LUA metatables: The URL example.
21st September, 2011
Scripting, Tutorials
This tutorial teach you an easy way to manage your URL parameters in your application by using LUA metatables.
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
Metatables in LUA are a kind of hashtable. You can associate a key and a value. Here, the key can be anything (number, string, object…)
The URL post parameters is a list of “parameter_key=parameter_value”, separated by “&”.
We will use the parameter_keys as key of a metatable, and parameter_values as value.
Steps
1. In your game, where you want to create an url, declare the metatable like that:
local params = {}
2. Now, add all the parameters you want for your URL by adding each key and value of the parameter in the metatable, using this syntax:
params["page"]=""..this.nCurrentPage ( ) params["category"]=this.sCurrentCategory ( )
3. Create a function buildPost ( params ), taking in argument your metatable containing the URL parameters.
4. Start by declaring the result variable:
local sRes = ""
5. We will now create a loop for the metatable. For this kind of table, you mustn’t use the “for i” loop, but the “for each” one.
The syntax of this loop is:
for vKey in params do local vValue = params[vKey] end
6. Concat the key and the value, by adding a “=” between them. Do not forget to encode the value. Then add the param to the sRes variable.
local sParam = vKey.."="..string.encoreURL ( vValue ) sRes = sRes..sParam.."&"
7. At the bottom of the function, do not forget to remove the last “&”, and return the final string:
sRes = string.getSubString ( sRes, 0, string.getLength ( sRes ) - 1 ) return sRes
The whole function should now looks like that:
-------------------------------------------------------------------------------- function Facebook.buildPost ( params ) -------------------------------------------------------------------------------- local sRes = "" for vKey in params do local vValue = params[vKey] local sParam = vKey.."="..string.encoreURL ( vValue ) sRes = sRes..sParam.."&" end sRes = string.getSubString ( sRes, 0, string.getLength ( sRes ) - 1 ) return sRes -------------------------------------------------------------------------------- end --------------------------------------------------------------------------------
8. Get back to the place where you have declared the metatable, and add this line:
local sUrl = this.sTheServerUrl ( )..”/search?”..this.buildPost ( params )
You can now use the url
Conclusion
By using this way, you can now easily build URLs in your game, just by creating a metatable, adding the post parameters in it and calling your buildPost function.
Leave a Reply






