lua:如何将我的函数绑定到io库

lua:如何将我的函数绑定到io库,lua,Lua,我编写了一个lua函数write_json,它将lua表转换为json文本。 是否可以将函数与io库绑定,以便我可以这样使用它: mytable = {name="Jack", age="22", score=[12,33,55,66]} f = io.open("score.json", "wb") f:write_json(mytable) -- call my function here. f:close() io.open返回的对象类型是userdat

我编写了一个lua函数write_json,它将lua表转换为json文本。 是否可以将函数与io库绑定,以便我可以这样使用它:

    mytable = {name="Jack", age="22", score=[12,33,55,66]}

    f = io.open("score.json", "wb")
    f:write_json(mytable) -- call my function here.
    f:close()

io.open
返回的对象类型是
userdata
,我认为由于其独特的性质,无法对其进行修补。

您需要访问文件对象元表的
\u index
表,并将新方法放在那里:

local metatable = getmetatable( io.stdout )
local indextable = metatable.__index
indextable.write_json = function( file, tab )
  -- ...
end
还有另一种方法:C API函数
luaL_newmetatable
将文件对象的metatable存储在注册表项
“file*”
下,因此以下方法也可以使用(但需要调试库):

还有另一种(更黑客的)方法:我测试过的所有Lua版本(PUC Rio Lua 5.1、5.2、5.3和LuaJIT)都将元表的
\uuu index
字段设置为元表本身,这样您就可以访问
\uu index
表,如下所示:

local indextable = io.stdout.__index

最好的方法可能是第一种。

试试
io.write\u json=which
,但我不建议弄乱内置内容。@ColonelThirtyTwo这样,我如何访问“write\u json”中的文件对象。有一个“自我”指针吗?@ColonelThirtyTwo-它不工作。我找到了这个。同样的想法,但它必须传递一个文件对象作为api的第一个参数。不完全是我所期望的装订。
local indextable = io.stdout.__index