banming / banminglualab Goto Github PK
View Code? Open in Web Editor NEWLua学习实验
Lua学习实验
当我使用你的代码 LuaJson 的时候,按照例子书写转化一个空table为json的时候,出现一个问题
代码如下
#!/usr/bin/lua require("LuaJson") local jsonStr=luaJson.table2json({}) print(jsonStr)
返回的结果只有一个} 这样应该是不合理的,后来查看了您的代码,发现这个函数这样定义的
function luaJson.table2json(tab) local str = "{" for k, v in pairs(tab) do if type(v) == "string" then str = str .. string2json(k, v) elseif type(v) == "number" then str = str .. number2json(k, v) elseif type(v) == "boolean" then str = str .. boolean2json(k, v) elseif type(v) == "table" then str = str .. table2json(k, v) end end str = string.sub(str, 1, string.len(str) - 1) return str .. "}" end
发现主要代码是这个for循环完毕后处理了一下这个str,进行了截取,导致第一个{不见了,我也是初学者,不过我的建议是将这段处理截取的代码和for循环作为一个整体放入一个if判断的代码块中,例如我们先判断table是否为空再循环:
function luaJson.table2json(tab) local str = "{" if _G.next(tab) ~=nil then for k, v in pairs(tab) do if type(v) == "string" then str = str .. string2json(k, v) elseif type(v) == "number" then str = str .. number2json(k, v) elseif type(v) == "boolean" then str = str .. boolean2json(k, v) elseif type(v) == "table" then str = str .. table2json(k, v) end end str = string.sub(str, 1, string.len(str) - 1) end return str .. "}" end
我本地测试了一下,这段代码加上去后 {}空table回转化为'{}'了
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.