I
I
IlliumOld2018-09-19 09:11:04
Lua
IlliumOld, 2018-09-19 09:11:04

Can an if in lua check for the presence of elements in an array?

Good afternoon, ladies and gentlemen.
Can an if in lua check if values ​​exist in a declared array? In other words, is the code equivalent to:

local currentTable = {}
if currentTable then

Here is this code:
local currentTable = {}
if #currentTable ~= 0 then

And which comparison option is faster?
UPD. Also, the second option will not work correctly if the elements in the table are not presented sequentially. How would the first option work in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
IlliumOld, 2018-09-19
@IlliumOld

Not equivalent. The code below will check if currentTable exists. if is meaningless because currentTable is declared and exists:

local currentTable = {}
if currentTable then

The code below will iterate through the currentTable elements in order and count their number.
local currentTable = {}
if #currentTable ~= 0 then

When:
local a = "name"
local currentTable = {a="eman"}
if #currentTable ~= 0 then

if again makes no sense, because the first element of the currentTable will be the name element with the value "eman". There is nothing to count, #currentTable element counter will show 0 because currentTable[1] = nil.
I did the check like this:
function IsEmpty(t)
    if not t then
        return true
    end
    for _, _ in pairs(t) do
        return false
    end
    return true
end
local currentTable = {}
if not IsEmpty(currentTable) then

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question