【问题标题】:How to call a function from other script in LUA?如何从 LUA 中的其他脚本调用函数?
【发布时间】:2019-06-02 08:39:03
【问题描述】:

我有一个名为“root”的根文件夹。 在这个文件夹中,我还有 2 个目录,每个目录都有一个文件夹,每个目录都有一个脚本:

/root/script01/client_script01/main.lua

在这个脚本中我有这个:

local function OpenWindow()
    stuff
end

/root/script02/client_script02/main.lua

我想在第二个脚本中使用OpenWindow() 函数!

【问题讨论】:

    标签: function lua


    【解决方案1】:

    如果你在定义中不使用local关键字,你可以从client_script02/main.lua调用OpenWindow是正确的。

    但这不是最佳做法。我不确定您的环境或意图的细节,但在大多数情况下,最好创建一个 lua 模块并使用 require 函数来加载它。

    这样更好,因为它显示了文件之间的关系,表明client_script02/main.lua需要加载client_script01/main.lua才能正常运行。

    您的模块可能如下所示:

    local client_script01 = {}
    
    client_script01.OpenWindow = function()
        --stuff
    end
    
    return client_script01
    

    另一个脚本是这样的:

    local cs01 = require('client_script01')
    
    do
        cs01.OpenWindow()
        --stuff
    end
    

    您还需要根据require 函数执行搜索的方式调整文件结构以更好地适应此约定:lua-users - Package Path

    【讨论】:

      猜你喜欢
      • 2010-11-15
      • 2018-04-23
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 2019-10-12
      相关资源
      最近更新 更多