如何在Lua中定义变量以及如何在Cocos2d-x中的其他Lua脚本中调用它。

如何在Cocos2d-x的Lua脚本中定义变量(常量),以及如何在其他Lua脚本中调用它?

我通常的做法是:

main.lua

local r = require("src/Square")
local constant = r:getConstant()

Square.lua

function Square:getConstant()
    return 10
end

是否有其他更优雅的方法?欢迎提出任何建议。

点赞
用户201863
用户201863

你可以将它定义成一个全局变量:

constant = r:getConstant()

但是这个变量并不是常量。Lua 不支持不可变、只读或常量变量的概念。

有一些技巧可以使用 Lua 表的元表来防止值被修改,但这要求值必须在表中,并且无法防止表本身被修改(例如设置为 nil 或其元表被替换)。

简单地使用一个返回常量值的函数是确保值被视为常量的更简单的方式。

我过去还使用过一种标记常量值的符号表示方式,例如:

_constant = 10
local _localConstant = 11

前缀 _ 将变量标记为常量。或者,如果这些值在 C/C++ 或常用的框架中是已知的常量,可以使用 ALL-CAPS 风格的类似于 #define 宏的方式(例如 DBL_EPSILONM_PI_2)。这只是为程序员提醒。

最后,还有一个叫做“const”的表是全局表,定义了一些假定的常量值:

const = {thisIsTen = 10, thatIsEleven = 11}

使用表可以清楚地表明这些是常量:

result = 100 * const.thisIsTen
2014-08-26 10:12:07
用户2248354
用户2248354

如果您正在寻找一个只读的常量值,不能更改,您需要为此创建一个函数(您已经有了)。您还需要知道的是,Lua按值而不是引用返回基本类型(数字,布尔,nil,字符串)(仅当您通过创建返回它们时)。

以下是此功能的替代方法:

square.lua

Square = {}
Square.__index = Square

local _const = 10

function Square:GetConst()
    local const = _const
    return const
end

-- Test function
function Square:MoveUp()
    _const = _const + 2
end

return Square

main.lua

local sr = Require("src/Square")

print(sr:GetConst()) -- 10

local plus = sr:GetConst() + 4

print(sr:GetConst(), plus) -- 10     14

sr:MoveUp()

print(sr:GetConst()) -- 12

还要注意,Square可以更改为一个本地函数(推荐),因此在这种情况下,下一次创建对象时不会有任何麻烦。

2014-08-26 13:17:03