As I’m typing away here on the code for Kepler, there is a part of the game where I need the function of a switch to turn an object on and off. Lua does not natively support a switch function like some C languages and makes the “what should be simple process”, into a beat around the bush until you get a similar effect. After much browsing of the web, everyone’s examples were very long and extremely complex. I had a switch function before in the old code, however it was not very efficient and somewhat buggy. I took it upon myself to make a fresh, new, SIMPLE switch function that works like a charm and is error free! Here is a code example of turning a light on and off that I made that you are more than welcome to use!
–SIMPLE LUA SWITCH FUNCTION by Nexus Game Studio (09/30/11)
W = display.contentWidth
H = display.contentHeight
–Displays a basic red rectangle that is placed in the center of the screen
–This is a button
button = display.newRect (50,50,50,50)
button.x = W / 2
button.y = H / 2
–Displays a basic yellow circle that is placed above the button
–This is a light
light = display.newCircle (50,50,50)
light.x = W / 2
light.y = H / 4
light.isVisible = false –Turn visible to false if you want the light to be off initially, if you want it to be on initially, delete this line
local power = true
–Tap function that detects when the user has touched the red switch. You can replace “.isVisible” with any function of your own choosing.
if (power == false) then
light.isVisible = false
power = true
light.isVisible = true
power = false
–Event listener that calls the button function when the red box is touched.
button:addEventListener( ‘tap’, button)
I hope this helps anyone out who is looking for a simple solution to creating a switch function in Lua. This code is built for development on iOS, specifically Corona SDK (hence the “tap” functions) so if used for development on other platforms, feel free to modify the code to your preferred input. This is my attempt at it, if anyone else has ideas for a simpler or more efficient version, feel free to share.