Fast in_array or in_list implemented Lua?

On lua mailing list somebody asked if there is any way to check very short if an element is in a specific list of elements.

In php you would do for example

if (in_array("A",array("A","B","C")) ) { echo "hello"; }

Of course, everyone can write a short in_table function in lua:

function in_table ( e, t )
    for _,v in pairs(t) do
        if (v==e) then return true end
    return false

But Asko answered a clever and very short way:

if ({A=1,B=1,C=1})["A"]  then print("hello") end

Why does that work?

{A=1,B=1,C=1} creates nothing but a table with following style:

[A] => 1
[C] => 1

(used print_r for lua here)

So what does ({A=1,B=1,C=1})["A"] do then? It returns the value of the table's ["A"]-Field. And this is 1! Thatswhy the 'then'-branch will be used.

Basicly its using lua's all table entries are set or nil way to check whether a element is set as key in the temporary table or not.

So if you use your own lua implementation for in_table or do it that tricky way is your choice!

In lua, open source by @ 11 Nov 2007

comments powered by Disqus

Recent Files


Recent Dev-Articles

Read recently