gpt4 book ai didi

variables - 自定义变量类型 Lua

转载 作者:行者123 更新时间:2023-12-02 23:16:40 25 4
gpt4 key购买 nike

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

最佳答案

您无法创建新的 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

输出:

table: 004649D0table: 004649F8----The type of x is: frobnicatorThe type of y is: frobnicator----Frobnicator object  field1 = nil  field2 = nilFrobnicator object  field1 = 1  field2 = hello----stringtable

当然这个例子很简单,关于Lua中的面向对象编程还有很多东西要说。您可能会发现以下引用资料很有用:

关于variables - 自定义变量类型 Lua,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348745/

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