【问题标题】:(Lua) Simple metatable in another file(Lua) 另一个文件中的简单元表
【发布时间】:2022-01-07 13:03:15
【问题描述】:

很抱歉,这是一个如此基本的问题,但我似乎无法理解。我是 Lua 的初学者,所以我有几个问题。

我的目标是制作一个小的“类”Vector3。我正在使用一个放在文件 vector3.lua 中的元表。

1) 由于我的元表 Vector3 与我的 main.lua 位于单独的文件中,我是否正确假设我正在编写一个“模块”?这与将我的代码与我的 main 放在同一个文件中真的不同吗?

1.5) 如果我正在编写一个模块,有没有办法创建一个“新”函数以在 main 中使用这种语法:

v = Vector3(3, 2, 4)

假设我将我的 vector3.lua 导入为

local Vector3 = require "Vector3"

?

2) 是否所有模块都需要

return Vector3

在模块的末尾?为什么?

3) 最后,我无法理解我的编译错误。 这些是我的文件:

vector3.lua

local Vector3 = {} 
Vector3.__index = Vector3

local function new(x, y, z)
    return setmetatable( {x=x, y=y, z=z} , Vector3 )
end

local function Vector3:__tostring() -- this is my 8th line in my editor (the error line)
    return "(x:" .. self.x .. ", y:" .. self.y .. ", z:" .. self.z .. ")"
end

local function Vector3.__newindex()
    print("You cannot add another axis to a vector3")
end

return Vector3

ma​​in.lua

local Vector3 = require "Vector3"

v = Vector3.new(3, 2, 4)

print(v)

我的错误

$ lua main.lua
lua: error loading module 'Vector3' from file './Vector3.lua':
    ./Vector3.lua:8: '(' expected near ':'
stack traceback:
    [C]: in ?
    [C]: in function 'require'
    main.lua:1: in main chunk
    [C]: in ?

可能是什么问题?

4) 即使我注释了我的 :__tostring() 和 .__newindex 函数,这也是我得到的另一个错误:

$ lua main.lua
lua: main.lua:3: field 'new' is not callable (a nil value)
stack traceback:
    main.lua:3: in main chunk
    [C]: in ?

这是另一个问题还是因为我的元表除了 new 之外没有其他功能(是否被覆盖(我正在考虑 __add 等)?

感谢您的宝贵时间!

【问题讨论】:

    标签: module lua metatable


    【解决方案1】:

    为了将来的通知,您应该在单独的帖子中提出这些问题。

    1. 将编码放在一个单独的文件中使得更容易重用和封装你的类。

      1.5 定义__call 元表并让它调用new

    2. 最好在模块文件中定义为本地,然后在文件末尾返回该值以防止全局名称冲突,允许调用者选择名称。

    3. 你必须在使用表时定义一个类似function Vector3:__tostring()的函数,你不能使用本地(也没有必要,因为函数将包含在表中)。

    4. 您忘记将new 定义为向量类Vector3.new 的一部分

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 2023-02-17
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 2017-07-16
      • 2013-05-13
      • 2015-01-21
      • 2016-05-06
      相关资源
      最近更新 更多