Passing variables into a function in Lua

Tag: function , lua , corona Author: zhang19780925 Date: 2011-05-01

I'm new to Lua, so (naturally) I got stuck at the first thing I tried to program. I'm working with an example script provided with the Corona Developer package. Here's a simplified version of the function (irrelevant material removed) I'm trying to call:

function new( imageSet, slideBackground, top, bottom )

    function g:jumpToImage(num)

            local i = 0
            print("#images", #images)
            for i = 1, #images do
                if i < num then
                    images[i].x = -screenW*.5;
                elseif i > num then
                    images[i].x = screenW*1.5 + pad
                    images[i].x = screenW*.5 - pad
            imgNum = num


If I try to call that function like this:

local test = myImages )

I get this error:

attempt to compare number with nil

at line 225. It would seem that "num" is not getting passed into the function. Why is this?

Best Answer

Where are you declaring g? You're adding a method to g, which doesn't exist (as a local). Then you're never returning g either. But most likely those were just copying errors or something. The real error is probably the notation that you're using to call test:jumpToImage.

You declare g:jumpToImage(num). That colon there means that the first argument should be treated as self. So really, your function is g.jumpToImage(self, num)

Later, you call it as test.jumpToImage(2). That makes the actual arguments of self be 2 and num be nil. What you want to do is test:jumpToImage(2). The colon there makes the expression expand to test.jumpToImage(test, 2)

Take a look at this page for an explanation of Lua's : syntax.


Okay, that did the trick. Thanks a lot! :)