tablelib是一个使用C++实现的动态库,提供给lua使用。
tablelib is a dynamic library implemented in C++ for lua.
将tablelib.dll或tablelib.so文件放到你的lua项目的目录下,或者添加到你的环境变量中。
Put the tablelib.dll or tablelib.so file in your lua project directory, or add it to your environment variables.
local tablelib = require "tablelib"
-- tostring
local s = tablelib.tostring({value = 1})
print(s)
-- {value = 1}
-- tojson
local tb = {["value"]=1,["array"]={[1]=1,[2]=2,},["hash"]={[100]="string",},}
local json = tablelib.tojson(tb)
print(json)
-- {"array":{"1":1,"2":2,"_int_keys_":["1","2"]},"value":1,"hash":{"100":"string","_int_keys_":["100"]}}
-- loadjson
local tb = tablelib.loadjson(json)
print(tablelib.tostring(tb))
-- {["value"]=1,["array"]={[1]=1,[2]=2,},["hash"]={[100]="string",},}tostring函数可以接收任意参数。如果参数不是一个table,它会返回参数的字符串表示。- The
tostringfunction can accept any argument. If the argument is not atable, it will return the string representation of the argument. tostring函数可以安全地处理table中的循环引用。它会标记已访问过的元素,避免无限递归。- The
tostringfunction can handle circular references in tables safely. It will mark the visited elements and avoid infinite recursion. - 如果你在编译库时添加了
-D_OPEN_HEX_选项,它会把数值类型转为16进制字符串,性能优于10进制字符串。 - If you compile the library with the
-D_OPEN_HEX_option, it will convert numeric values to hexadecimal strings, which have better performance than decimal strings. - 如果你的
table有__pairs元方法,那么tostringtojson可能无法按照你的预期工作,它不会调用__pairs元方法来遍历table。 - If your table has a
__pairsmetamethod, thentostringtojsonmay not work as you expect. It will not call the__pairsmetamethod to iterate over the table. tojson函数会将一个table转为json格式的字符串, 为了解决table数值key过于稀疏的问题, 会将所有的数值key(包括浮点数)转为string, 并添加_int_keys_字段, 它是一个数组, 会记录有哪些数值key被转换, 例如 :{["value"]=1,["array"]={[1]=1,[2]=2,},["hash"]={[100]=999,},}将会被转为:{"array":{"1":1,"2":2,"_int_keys_":["1","2"]},"value":1,"hash":{"100":999,"_int_keys_":["100"]}}- The
tojsonfunction will convert atableto ajsonformat string. To solve the problem of sparse numeric key intable, it will convert all numerickey(including floating point numbers) tostring, and add_int_keys_field. It is an array that records which numerickeyare converted1. For example :{["value"]=1,["array"]={[1]=1,[2]=2,},["hash"]={[100]=999,},}converted to :{"array":{"1":1,"2":2,"_int_keys_":["1","2"]},"value":1,"hash":{"100":999,"_int_keys_":["100"]}} loadjson函数会将json格式的字符串转为table, 如果存在_int_keys_字段, 会遍历_int_keys_, 将对应的key转为number- The
loadjsonfunction will convert ajsonformat string to atable. If the_int_keys_field exists, it will iterate through_int_keys_and convert the correspondingkeytonumber. - 如果你的
table中存在相同名字的number key和string key, 那么tojson转换后的结果将是错误的, 例如 :{[1] = "number", ["1"] = "string"}, 转为json后 :{"1":"string","1":"number","_int_keys_":["1"]} - If your
tablecontainsnumber keyandstring keywith the same name, then the result oftojsonconversion will be wrong, for example:{1 = "number", ["1"] = "string"}, converted to json:{"1":"string","1":"number","int_keys":["1"]}.