Lua 中将变量传递给函数
我是 Lua 新手,所以(自然地)我在尝试编程的第一件事上就陷入了困境。我正在使用 Corona Developer 包提供的示例脚本。这是我尝试调用的函数的简化版本(删除了不相关的材料):
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
如果我尝试像这样调用该函数:
local test = slideView.new( myImages )
test.jumpToImage(2)
我收到此错误:
尝试将数字与nil进行比较
在第 225 行将 number 与 nil 进行比较。看起来“num”没有被传递到函数中。这是为什么呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你在哪里声明
g
?您正在向g
添加一个方法,该方法不存在(作为本地方法)。那么你也永远不会返回 g 。但很可能这些只是复制错误或其他错误。真正的错误可能是您用来调用 test:jumpToImage 的符号。您声明
g:jumpToImage(num)
。那里的冒号意味着第一个参数应该被视为 self 。所以实际上,您的函数是g.jumpToImage(self, num)
稍后,您将其称为
test.jumpToImage(2)
。这使得 self 的实际参数为 2,num 为 nil。您要做的是test:jumpToImage(2)
。那里的冒号使表达式扩展为test.jumpToImage(test, 2)
看一下 此页面了解 Lua 的
:
语法的解释。Where are you declaring
g
? You're adding a method tog
, 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 asself
. So really, your function isg.jumpToImage(self, num)
Later, you call it as
test.jumpToImage(2)
. That makes the actual arguments ofself
be 2 andnum
be nil. What you want to do istest:jumpToImage(2)
. The colon there makes the expression expand totest.jumpToImage(test, 2)
Take a look at this page for an explanation of Lua's
:
syntax.