Nexus Game Studio – Independent Game Developer

Lua Switch Function Code Example

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:setFillColor(255,0,0)
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:setFillColor(255,255,0)
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.
function button:tap(event)

if (power == false) then

light.isVisible = false
power = true
else
light.isVisible = true
power = false

end

end

–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.

 

12 comments

  1. August 30, 2011 at 7:30 pm

    Here’s a modification to your tap function:

    function button:tap(event)
    light.isVisible = (power ~= false)
    power = not power
    end

    It’s shorter, although I’ll admit it *is* more complex. But by doing it this way you can do away with the “IF” logic and make it more concise.

    Thanks for posting this, toggling something on/off comes up in quite a few situations.

    Jay

  2. August 30, 2011 at 9:03 pm

    Thanks for the alternative!

  3. August 31, 2011 at 1:37 am

    [...] http://www.nexusgamestudio.com/2011/08/30/lua-switch-function-code-example/ Sidebar: When writing sample code I don’t always write generically myself, so I’m not picking on the guys at Nexus Game Studio — they created a cool sample and with their permission I’m using it as a starting point for this example. [...]

  4. kingsley
    March 23, 2012 at 9:35 am

    here is my code

    unction gforce ()
    gravity = physics.setGravity( .0, .10)
    gravity = false
    end

    on = true

    local function dot3 ()

    local pdot = display.newImage( “assets/graphics/purpleDot.png”)
    pdot:setReferencePoint(display.centerReferencePoint)
    pdot.x = _W/2
    pdot.y = 500
    physics.addBody( pdot,”static”, { density = -0.0, friction = 0.3, bounce = 0.0, radius = 32 } );

    pdot:addEventListener(“touch”, slow_pop)
    pdot:addEventListener(“touch”, pdot )

    function pdot:touch(event)
    if (on == false) then
    gforce = false
    on = true
    else
    gforce = true
    on = false

    end
    end
    end
    timer.performWithDelay(3000, pdot, 1)

    function slow_pop (event)
    if(event.phase == “ended”) then
    audio.play(pop)
    end
    end

    tmr = timer.performWithDelay(0,dot3, 1);

    what am I going wrong here

    and second what do you call the art style of your new space game

  5. kingsley
    March 23, 2012 at 12:41 pm

    I’m sorry i didnt put any detail in the comment but what im trying to do is use your switch to turn on and off physics.setGravity( .0, .10) to give it a slow motion effect

  6. March 23, 2012 at 1:37 pm

    Hey Kingsley,

    I’ll be happy to help you out.

    What are you exactly trying to accomplish. Change the gravity after you touch ‘pdot’, and then change back to normal gravity when you touch ‘pdot’ again?

    And for the art style, it’s abstract style set in space. Although what you see here on our site is old art concepts and Stephen has been working hard on new ideas for abstract syles.

    Brian P.

  7. kingsley
    March 23, 2012 at 2:25 pm

    hey Brian

    Thanks for writing back and what I’m trying to accomplish is when you touch/tap pdot physics.setGravity( .0, .10) turns on and and then when you touch/ tap pdot again it goes back to normal so yes what you said was right.

    But in the long run what I really want to do is make a accelerometer I hope thats the word so when you touch a amount of dots on the screen with out touching anything else it will activate the switch which will run for 3 or 4 seconds.

    it’s like rewarding the player with an extra bonus for playing so well

    I know thats a lot

    I’m new to corona and lua and kinda to programing and scripting so I’m learning while trying to make a little game. hopping one day I could become a indie style game developer.

    I like the art especially how it give off a glow/ illuminate

  8. March 23, 2012 at 2:26 pm

    I just whipped this up quickly for you to check out (plug and play)

    W = display.contentWidth
    H = display.contentHeight

    –Require physics library
    physics = require”physics”

    –Initiate physics engine
    physics.start()

    –Set initial gravity
    physics.setGravity(0, 1)

    –set draw mode (optional)
    physics.setDrawMode(“hybrid”)

    –Create white circle and place at top of screen
    local pdot = display.newCircle( 0,0,20,20)
    pdot:setReferencePoint(display.centerReferencePoint)
    pdot.x = W/2
    physics.addBody( pdot,”dynamic”, { density = 1, friction = 0.3, bounce = 0, radius = 20 } );

    –Create ground for circle to bounce and react with
    local ground = display.newRect( 0,0,W, 20)
    ground.y = H
    physics.addBody( ground,”static”, { density = 1, friction = 0.3, bounce = 0.5 } );

    –Boolean for switch function
    slow = false

    –Switch function for slow motion
    local function slowMode()
    if slow == false then
    slow = true
    pdot.linearDamping = 1.5 — Set linearDamping to 1.5 (slows object linear velocity)
    print(“on”) — Print “on” in terminal to show that this is functioning
    elseif slow == true then
    slow = false
    pdot.linearDamping = 0 — Set linearDamping to 0 (resume original linear velocity)
    print(“off”) — Print “on” in terminal to show that this is functioning
    end
    end

    pdot:addEventListener(“tap”, slowMode)

    I don’t advise changing the gravity to simulate a slow motion effect on an object, since the objects linear velocity wont slow down if gravity is decreased. You need to effect the linear velocity either by adding applyForce or setLinearVelocity. I used linearDamping because I found it provided the best ‘slow motion’ effect, however use what works for your application.

    Hope this helps.

    Brian P.

  9. March 23, 2012 at 2:28 pm

    P.S. , You’ll have to reset all the quotations in your script editor if you copy paste from this page, something to do with formatting I think.

  10. kingsley
    March 23, 2012 at 2:47 pm

    oh nice that was fast lol it toke me 3 or 4 days to get where im at this is my code as of now I guess when i get back home i’ll put see whats what and see how to put it in my code.

    please tell me if in going in the right way oh and you can see how i was trying to use your on and off switch

    —————————————————————————————-

    – main.lua

    —————————————————————————————–

    – Your code here

    _H = display.contentHeight;
    _W = display.contentWidth;
    mR = math.random;
    numberOfBule = 45;
    numberOfRed = 15;
    local physics = require(“physics”);
    physics.start();

    –physics.setDrawMode( “hybrid” )

    –sounds and soundtrack
    local pop = audio.loadSound(“assets/media/pop01.wav”);
    local fart = audio.loadSound(“assets/media/fart.wav”);
    ————————————————————————

    function removeDot(obj)
    obj:removeSelf()
    end

    local function dots()
    local dot = display.newImage( “assets/graphics/blueDot2.png”,45, 45)
    dot:setReferencePoint(display.centerReferencePoint);
    dot.x = mR(60, _W – 50);
    dot.y = mR(70, _H – 50);
    physics.addBody( dot, { density = -1.0, friction = 4.3, bounce = 0.2, radius = 32 } );

    function dot:touch(event)
    if (event.phase == “ended”) then
    audio.play(pop);
    removeDot(self)
    return true
    end
    end

    dot:addEventListener(“touch”, dot)
    end

    tmr = timer.performWithDelay(1000,dots, numberOfBule);

    local function dots2()
    local dot2 = display.newImage( “assets/graphics/redDot.png”,14, 14)
    dot2:setReferencePoint(display.centerReferencePoint);
    dot2.x = mR(60, _W – 50);
    dot2.y = mR(70, _H – 50);
    physics.addBody( dot2, { density = 1.0, friction = 0.3, bounce = 1.5, radius = 14 } );

    dot2:addEventListener(“touch”, fart_n)

    end
    function fart_n(event)
    if(event.phase == “ended”) then
    audio.play(fart)
    end
    end
    tmr = timer.performWithDelay(3000,dots2, numberOfRed);

    local floor = display.newRect(0,0, _W,20);
    floor:setReferencePoint(display.centerReferencePoint);
    floor.x = _W/2
    floor.y = 500

    function gforce ()
    gravity = physics.setGravity( .0, .10)
    gforce.isVisible = false
    end

    on = true

    local function dot3 ()

    local pdot = display.newImage( “assets/graphics/purpleDot.png”)
    pdot:setReferencePoint(display.centerReferencePoint)
    pdot.x = _W/2
    pdot.y = 500
    physics.addBody( pdot,”static”, { density = -0.0, friction = 0.3, bounce = 0.0, radius = 32 } );

    pdot:addEventListener(“touch”, slow_pop)
    pdot:addEventListener(“touch”, pdot )

    function pdot:touch(event)
    if (on == false) then
    gforce.isVisible = false
    on = true
    else
    gforce.isVisible = true
    on = false

    end
    end
    end
    timer.performWithDelay(3000, pdot, 1)

    function slow_pop (event)
    if(event.phase == “ended”) then
    audio.play(pop)
    end
    end

    tmr = timer.performWithDelay(0,dot3, 1);

    local roof = display.newRect(0,0, _W,20);
    roof:setReferencePoint(display.centerReferencePoint);
    roof.x = _W/2
    roof.y = -38

    local left_wall = display.newRect(0,0,1, _H);
    left_wall:setReferencePoint(display.centerReferencePoint);
    left_wall.x = 0-left_wall.width/2
    left_wall.y = _H/2

    local right_wall = display.newRect(0,0,5, _H);
    right_wall:setReferencePoint(display.centerReferencePoint);
    right_wall.x = _W+right_wall.width/2
    right_wall.y = _H/2

    physics.addBody(floor, “static”, {friction = 0.3, bounce = 0.2} );

    physics.addBody(roof, “static”, {friction = 0.3, bounce = 0.2} );

    physics.addBody(left_wall, “static”, {friction = 0.3, bounce = 0.2} );

    physics.addBody(right_wall, “static”, {friction = 0.3, bounce = 0.2} );

  11. kingsley
    March 23, 2012 at 3:01 pm

    I was reading about applyForce, setLinearVelocity and linearDamping on a forum I think it was stackfollow or something like that but it seemed a little confusing and then someone said why don’t you just use physics.setGravity I plugged it in to my code and played with the x and y and saw that all my dots moved slow but I see what your saying about linear velocity

    I was hoping i could set my function gforce to isVisible to make it work and i was looking to see what was equivalent to isVisible for functions if there is a such thing

    and when I get back from work i’ll read up on linear velocity and then look at your code so that I can get a full understanding

    thank you I appreciate you helping me

  12. March 23, 2012 at 3:03 pm

    Here, E-mail me at ‘brian-nexus@live.com’ and I’ll help you further via email so we don’t have to clutter up this comment section. :P

    Brian P.

Leave reply

Back to Top