【问题标题】:lua : passing parameter to other function problemlua:将参数传递给其他函数问题
【发布时间】:2011-11-01 14:58:48
【问题描述】:

不确定是否有人遇到过这种问题。这是我的代码

在 main.lua 中:

local highScore = require("highScore")
local username = "myName"
local finishedTime = 12345

highScore:InsertHighScore(userName, finishedTime)

在 highScore.lua 中

function InsertHighScore(name,time)
   print(name)
   print(time)
   -- other code
end

它看起来很简单,应该没有错,但在我的控制台中显示:

 table: 0x19e6340
 myName

经过一天的测试,我发现在我传递的2个参数之前,它实际上传递了另一个表给我,所以在highScore.lua上进行这些更改:

function InsertHighScore(table,name,time)
   print(table)
   print(name)
   print(time)
   -- other code
end

所以现在我的“其他代码”可以很好地工作,但为什么它在我的参数之前传递了一个表格?

【问题讨论】:

    标签: function methods parameters lua


    【解决方案1】:

    在 Lua 中,使用冒号而不是点来调用对象/表表示该对象/表应该作为第一个参数传递给函数(例如,作为 self)。如果你不关心这个,那就用点来调用函数:

    highScore.InsertHighScore(userName, finishedTime)
    

    【讨论】:

    • 好的......所以现在我看到了问题,所以点并不意味着它正在访问类的参数而不是调用函数?
    • 无论如何,感谢您快速干净的回复duskwuff,非常感谢您的帮助,谢谢=)
    • 访问参数和调用函数实际上是一回事highScore.InsertHighScore 获取函数作为参数,加上括号调用它。
    • table:func(arg1, arg2) 是 table.func(table, arg1, arg2) 的语法糖
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2012-04-16
    • 2014-06-04
    • 2020-06-27
    相关资源
    最近更新 更多