【发布时间】:2011-02-10 22:52:25
【问题描述】:
我发现 Lua 的范围规则有点混乱。我在下面提交了一个 Lua 脚本的 sn-p,以突出我想问的问题:
-- 'forward definitions'
-- could these be moved to the bottom of the script to 'tidy up' the script?
-- could these reside in another file imported by require 'filename' to tidy up the script even more?
[[ Note: This function is accessing variables defined later on/elsewhere in the script
and is also setting a variable (flag) which is then used elsewhere in the script
]]
function war_is_needed()
if (goodwill:extendsToAllMen() and peace) then
if player:isAppointedLeader() then
economy_is_booming = false
return true
else
economy_is_booming = nil
return true
end
else
economy_is_booming = nil
return false
end
end
world = WorldFactory:new('rock#3')
player = PlayerFactory:getUser('barney', world)
while (not player:isDead()) do
peace = world:hasPeace()
goodwill = world:getGoodwillInfo()
if war_is_needed() then
world:goToWar()
else
if (not economy_is_booming) then
player:setNervousState(true)
player:tryToStartAWar()
else
player:setNervousState(false)
player:liveFrivously()
end if
end
end
我的问题是(暂时忽略全局变量可以被认为是邪恶的):
- 能否将脚本顶部的函数移至脚本底部以“整理”脚本?
- 能否将脚本顶部的函数重构(即移动)到单独的文件“warfuncs.lua”中,然后通过将函数定义替换为需要“warfuncs.lua”来导入脚本?
在回答上述两个问题时,请记住,脚本顶部的函数正在访问脚本中稍后/其他地方定义的变量 并且还设置了一个变量(标志),然后在脚本的其他地方使用。
如果 Lua 嵌入在 C 或 C++ 中(可能在堆上创建对象),范围规则是否会改变?
【问题讨论】: