gpt4 book ai didi

c++ - Lua 变量作用域、函数前向声明和使用 'require' 语句重构 Lua 脚本

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:30 25 4
gpt4 key购买 nike

我发现 Lua 的作用域规则有点困惑。我在下面提交了一段 Lua 脚本来突出显示我想问的问题:

-- '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”中,然后通过将函数定义替换为 require“warfuncs.lua”来导入到脚本中?

在回答上述两个问题时,请记住脚本顶部的函数正在访问稍后/脚本中其他地方定义的变量并且还设置了一个变量(标志),然后在脚本的其他地方使用它。

如果 Lua 嵌入到 C 或 C++ 中(可能在堆上创建对象),作用域规则会改变吗?

最佳答案

war_is_needed 不能在 while 循环之后移动。如果 while 循环包含在函数中,则可以将 war_is_needed 移到它之后。由于一切都是全局的,所以第二个问题的答案是肯定的。

关于c++ - Lua 变量作用域、函数前向声明和使用 'require' 语句重构 Lua 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4957473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com