Lua   发布时间:2022-04-12  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了变量 – 自定义变量类型Lua大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在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: 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,但核心材料仍然适用.

大佬总结

以上是大佬教程为你收集整理的变量 – 自定义变量类型Lua全部内容,希望文章能够帮你解决变量 – 自定义变量类型Lua所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: