I am trying to implement a custom iterator which works like table.foreach in Lua, but in more "syntax friendly" manner. I came across following construction (not sure if it's done purely in Lua or some kind of C "hack" in the Lua source code.
-- creature is a collection of Creature objects
-- "ps" is used as a filter variable
foreach creature cre "ps" do
if cre.name ~= $name then
-- code...
end
end
I tried to play around with table.foreach, ipairs and so on - but can nowhere get the similar result to the mentioned code sample. Could you give me a hint how this could be implemented?
A new keyword requires either a preproccesor or modifying the language's grammar directly.
An approximation of this syntax can already be easily achieved without leaving the confines of the language by writing an iterator - a function that when provided to the generic
forcontinuously supplies values for the loop variables, until the first value it returns is nil.(More specifically, you usually write a function that creates (returns) an iterator.
pairsandipairsare examples of this.)nextis a function that when provided a table and a key, returns the next key and its associated value.You can extend this with metatables and the
__callmetamethod to shorten the syntax required to construct the iterator (properly constructed classes / objects / prototypes (i.e., OOP) in Lua already rely heavily on metatables).All this means that the syntax
is very achievable.
The full example, with a very basic iterator: