using Select Case – with Functions

If you have worked with C, javascript or similar languages, you must have definitely encountered the ‘switch’ or ‘Select Case’ commands which do not seem to be present in Lua and often miss it while developing.

Lua Language

The first thing to look for is the language, it is this that we shall take advantage of to create our select statement. We shall use arrays in Lua which are quite flexible. We can create these simply as

This creates an array into arr that is set as follows

Hash Tables/Referenced Array

In the example above we created an indexed array, we can also create hash tables or referenced arrays which is similar to what is also called a dictionary object in some other languages. So we could use it as

Now we can access these as

References and Pointers

One of the reason that Lua is flexible is that everything is a reference to allocated memory. Therefore when you try to print a table or a function you get the memory address printed instead as seen in this code

Because everything is a pointer, we can simply assign another variable to point to this address.

we can call/invoke the function now either as theFunc() or newFunc()

Using this information for SelectCase

Now we can combine the two, arrays and the functions and use them together for Select Case as follows

and we can call the selectCase function as

In a C like syntax, this would look like

This can be adapted to cater for characters and words apart from numbers. We can create the array with a combination of numbers and hash as

and you can use it as

Practical Use

If you ask how is this useful, then here’s a scenario. Let’s say you have a shoot-em up type game and towards the end of the level you have the Boss Battle and as it progresses, the types of attack the boss enemy changes, basically you can create an array of these various attack types and then invoke them and change them. to provide an example,

and the currFormation can be incremented and called again to trigger another formation.

Closing thoughts

Hope this article helps you to understand a couple of things like arrays and functions. The way Lua works you can do some really nifty stuff.

Because the code above is pure Lua implementation, it can be used across the various frameworks. It can be used quite interestingly with those that have an OO flavour. One good example of using a framework leaning towards OO flavour is Gideros. You can download Gideros Studio from their website using a community license which is basically FREE.

Comments are closed.