加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

变量 – 自定义变量类型Lua

发布时间:2020-12-15 00:25:32 所属栏目:大数据 来源:网络整理
导读:我在lua中寻找一个库/函数,允许你有自定义变量类型(甚至可以使用“type”方法检测为自定义类型).我正在尝试制作一个自定义类型为“json”的json编码器/解码器.我想要一个只能在lua中完成的解决方案. 解决方法 您无法创建新的Lua类型,但您可以使用元表和表格
我在lua中寻找一个库/函数,允许你有自定义变量类型(甚至可以使用“type”方法检测为自定义类型).我正在尝试制作一个自定义类型为“json”的json编码器/解码器.我想要一个只能在lua中完成的解决方案.

解决方法

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

function frobnicator_metatable.ToString( self )
    return "Frobnicator objectn"
        .. "  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: 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中有很多关于面向对象编程的话要说.您可能会发现以下参考资料有用:

> Lua WIKI OOP index page.
> Lua WIKI page: Object Orientation Tutorial.
> Chapter on OOP of Programming in Lua.这是第一本书版本,因此它专注于Lua 5.0,但核心材料仍然适用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读