function - 在Lua中创建函数

标签 function lua coronasdk

当我通过赋值创建函数时,“if”条件不起作用,但是当我确实像下面的第二个示例那样创建函数时,它就起作用了。你能告诉我为什么吗?

无法运作:

local start=os.time()

local countDown = function(event)
   if((os.time()-start)==3) then
      Runtime: removeEventListener("enterFrame", countDown)
   end
   print(os.time()-start)
end

Runtime:addEventListener("enterFrame", countDown)

在职的:
local start=os.time()

local function countDown(event)
   if((os.time()-start)==3) then
      Runtime: removeEventListener("enterFrame", countDown)
   end
   print(os.time()-start)
end

Runtime:addEventListener("enterFrame", countDown)

最佳答案

那是因为当您执行local countDown = ...时,直到执行了countDown部分之后,...变量才存在。因此,您的函数将访问全局变量,而不访问尚不存在的局部变量。

请注意,Lua将local function countDown ...转换为以下内容:

local countDown
countDown = function ...

关于function - 在Lua中创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16999129/

相关文章:

C++ vptr 在每个对象中都是重复的

c# - 如何通过函数将字符串相加?

c - Lua - 重置脚本状态而不修复它

c++ - 在 C++ 和 Lua 之间来回发送变量指针?

coronasdk - 如何依次播放一个序列?

lua - 更改表中的变量

python - 如何从该列表中找到范围、平均值和前三个值而不出现类型错误?

c# - C# 中的泛型和函数

lua - Pandoc:Lua 过滤器,用于用 <div>abc</div> 替换 {{helloworld}}

lua - Math.random 非整数