开发者

Passing variables into a function in Lua

开发者 https://www.devze.com 2023-03-06 10:22 出处:网络
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 f

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)

            print(num)
            local i = 0
            print("jumpToImage")
            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
                else
                    images[i].x = screenW*.5 - pad
                end
            end
            imgNum = num
            initImage(imgNum)
        end

end

If I try to call that function like this:

local test = slideView.new( myImages )
test.jumpToImage(2)

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消