自定义变量类型Lua

Pot*_*Ion 7 variables lua

我在lua中寻找一个库/函数,允许你有自定义变量类型(甚至可以使用"type"方法检测为自定义类型).我正在尝试制作一个自定义类型为"json"的json编码器/解码器.我想要一个可以单独用lua完成的解决方案.

Lor*_*ica 13

您无法创建新的Lua类型,但您可以使用元表和表格在很大程度上模仿它们的创建.例如:

local frobnicator_metatable = {}
frobnicator_metatable.__index = frobnicator_metatable

function frobnicator_metatable.ToString( self )
    return "Frobnicator object\n"
        .. "  field1 = " .. tostring( self.field1 ) .. "\n"
        .. "  field2 = " .. tostring( self.field2 )
end


local function NewFrobnicator( arg1, arg2 )
    local obj = { field1 = arg1, field2 = arg2 }
    return setmetatable( obj, frobnicator_metatable )
end

local original_type = type  -- saves `type` function
-- monkey patch type function
type = function( obj )
    local otype = original_type( obj )
    if  otype == "table" and getmetatable( obj ) == frobnicator_metatable then
        return "frobnicator"
    end
    return otype
end

local x = NewFrobnicator()
local y = NewFrobnicator( 1, "hello" )

print( x )
print( y )
print( "----" )
print( "The type of x is: " .. type(x) )
print( "The type of y is: " .. type(y) )
print( "----" )
print( x:ToString() )
print( y:ToString() )
print( "----" )
print( type( "hello!" ) )  -- just to see it works as usual
print( type( {} ) )  -- just to see it works as usual
Run Code Online (Sandbox Code Playgroud)

输出:

table: 004649D0
table: 004649F8
----
The type of x is: frobnicator
The type of y is: frobnicator
----
Frobnicator object
  field1 = nil
  field2 = nil
Frobnicator object
  field1 = 1
  field2 = hello
----
string
table

当然这个例子很简单,在Lua中有很多关于面向对象编程的话要说.您可能会发现以下参考资料有用:


Obe*_*ron 5

您要求的是不可能的,即使使用C API也是如此.Lua中只有内置类型,没有办法增加更多内容.但是,使用元方法和表格,您可以创建(函数创建)与其他语言中的自定义类型/类非常接近的表.参见例如Lua中的编程:面向对象的编程(但请记住,本书是为Lua 5.0编写的,因此一些细节可能已经改变).