[lua] How do I know if a table is an array?
2017-02-27 17:10
405 查看
转自: http://stackoverflow.com/questions/7526223/how-do-i-know-if-a-table-is-an-array
down vote | The simplest algorithm to differentiate between arrays/non-arrays is this one:local function is_array(t) local i = 0 for _ in pairs(t) do i = i + 1 if t[i] == nil then return false end end return true end Explanation here: http://ericjmritz.name/2014/02/26/lua-is_array/ That said, you will still have issues with empty tables - are they "arrays" or "hashes"? For the particular case of serializing json, what I do is marking arrays with a field in their metatable. -- use this when deserializing local function mark_as_array(t) setmetatable(t, {__isarray = true}) end -- use this when serializing local function is_array(t) local mt = getmetatable(t) return mt.__isarray end |
相关文章推荐
- How do you check if a variable is an array in JavaScript? [duplicate]
- In Java, how can I test if an Array contains a certain value?
- [转]How to remove an assembly from the Cache if it is locked by Microsoft Installer
- Given an array of size N in which every number is between 1 and N, determine if there are any dupli
- How to Check if an Array Contains a Value in Java Efficiently?
- [Non-original]OS X How do I unset an IP address set with ifconfig?
- How to Check if an Array Contains a Value in Java Efficiently?
- How do I check if a type is a subtype OR the type of an object?
- How to judge if an iterator is used before.
- How to judge whether an array is empty?
- CareerCup Find if an array is a sequence
- How To Determinate If An EMCPOWER Partition Is Valid For ASMLIB
- How to Check if an Array Contains a Value in Java Efficiently?---reference
- how to know wether an element is exist in a html page.
- How can I set the background of UITableView (the tableview style is "Grouped") to use an image?
- How to tell if a file is an EXE or a DLL?
- 009:How can I test if an array contains a certain value?
- How to know if file is complete on the server using FTP
- Judging if an array is ascendingin a recursion way
- How do you test if an NSString is empty