Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua language: how use something similar to python list comprehensions

I'm new to Lua and I was wondering if there are some compact way to define a list, a metatable in Lua as we do in Python:

lis = [i for i in set if i>0]

Any example would be greatly appreciated.

like image 388
Ubuntu Silva Avatar asked Feb 03 '13 12:02

Ubuntu Silva


1 Answers

Lua has no native list

However as @joachim pointed out, the are some hacks you can use to achieve it.

local comp = require 'comprehension' . new()
comp 'table(v,k for k,v in pairs(_1))' {[3]=5, [5]=7} 

It would yield:

{[5]=3, [7]=5}

Notice that comprehension doesn't work in plain 5.2.x Lua. It requires Penlight Lua Libraries: http://stevedonovan.github.com/Penlight/api/index.html

You can also use MetaLua or LuaMacros

like image 80
ppaulojr Avatar answered Nov 10 '22 21:11

ppaulojr