Log In  

I am losing my mind over this very simple thing. These don't work:

next(table)==nil

table=={}

table==0

table==nil

This should be so simple but it's not working!! :(

P#39052 2017-04-03 17:32 ( Edited 2017-04-04 03:11)

Hack solution:

local empty = true
for g in all(grasses) do
empty = false
break
end
if (empty) then
level += 1
load_level(level)
end

still dont properly know how to check if a table is empty

P#39054 2017-04-03 17:56 ( Edited 2017-04-03 21:56)

"#table" is the length of the table, so you could check if "#table==0". I think that should work if you only want to know whether it's empty.

P#39056 2017-04-03 18:15 ( Edited 2017-04-03 22:16)

thank you!

P#39057 2017-04-03 18:18 ( Edited 2017-04-03 22:18)

Actually, after a little testing, this:

table={nil,2,nil}
print(#table)

showed 0, although I'm not sure why. And it doesn't seem like I can iterate through that table with

for t in all(table) do

So now I'm stumped, too. Hopefully someone else can shed some light on this.

P#39059 2017-04-03 18:35 ( Edited 2017-04-03 22:35)

> for k,v in pairs({1,2,3}) do print(k.." "..v) end
1 1
2 2
3 3

> for k,v in pairs({1,2,3}) do print(k.." "..v) end
2 2

When you set elements 1 and 3 to nil you effectively erase index 1 and 3. So "#T", intuitively, might therefore its behavior be testing for a series starting at one; thus, also miss non-numeric indices; indeed

> t={1,2,3}
> t.x=4
> print(#t)
3
> for k,v in pairs(t) do print(k.." "..v) end
1 1
2 2
3 3
x 4

So the #t function seems only relevant if using it as a stack or queue with always keeping index 1 full, which those add del all etc. functions are also oriented around

P#39065 2017-04-03 22:38 ( Edited 2017-04-04 02:54)
1

for tables where integer-valued keys don't form a contiguous sequence starting at 1, the result of # is implementation-defined, so it's often not helpful for those. # also isn't useful for finding non-integer keys. more information on #'s behavior is in the lua manual.

here's an example of a function that implements an emptiness check:

function is_empty(t)
    for _,_ in pairs(t) do
        return false
    end
    return true
end

try testing it with:

for x in all({{}, {1}, {1, 2}, {x='y'}}) do
    print(is_empty(x))
end
P#39066 2017-04-03 22:55 ( Edited 2017-04-04 03:17)

as for why next fails, pico-8 uses its own set of primitives distinct from lua's default ones, and next isn't one of them.

as for why table=={} fails, lua (as well as many other languages) goes against your intuition that this should compare two tables for structural equality; lua's table values are actually references to tables, and by default == compares these references. {} is a newly created table, and newly created tables are referentially distinct from previously created ones.

P#39067 2017-04-03 23:11 ( Edited 2017-04-04 03:11)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 18:42:18 | 0.007s | Q:19