Difference between revisions of "NETIO Lua Manual"

From wiki.netio-products.com
Jump to navigation Jump to search
(Loops)
(Tag: New redirect)
 
(27 intermediate revisions by 3 users not shown)
Line 1: Line 1:
== Loops ==
+
#REDIRECT [[Welcome to NETIO resources & projects & documentation overview]]
=== Numeric for ===
 
local arr = {2,3,7,5}
 
for i=1,#arr do logf("%d",arr[i]) end
 
<code><b>for</b> initVar,limit,increment <b>do</b></code>
 
* <i>number assignment</i> <code>initVar</code> inits loop-local variable
 
* <i>number</i> <code>limit</code> loops until initVar reaches this value
 
* <i>optional number</i> <code>increment</code> after each loop initVar increment by this value (default 1)
 
 
 
=== Generic for ===
 
Most common example (the order of elements in <code>pairs()</code> is not guaranteed)
 
local tab = {one=1, two=2, three=3}
 
for key,val in pairs(tab) do logf("%s:%d",key,val) end
 
Generic for syntax
 
for var_1, ..., var_n in explist do block end
 
is equivalent to (Full explanation [https://www.lua.org/pil/7.2.html here].)
 
do
 
  local _f, _s, _var = explist
 
  while true do
 
    local var_1, ... , var_n = _f(_s, _var)
 
    _var = var_1
 
    if _var == nil then break end
 
    block
 
  end
 
end
 
 
 
Iterator closure that holds its state
 
function iter(a)
 
  local i = 0
 
  return function()
 
    i = i+1
 
    return a[i]
 
  end
 
end
 
 
local arr = {2,3,7,5}
 
for value in iter(arr) do
 
  logf("%d",value)
 
end
 
 
 
Stateless iterator (in this case returns variable list: key and value)
 
function iter(a,i)
 
  i = i+1
 
  if a[i] then return i,a[i] end
 
end
 
 
local arr = {2,3,7,5}
 
for k,v in iter,arr,0 do
 
  logf("%d:%d",k,v)
 
end
 
 
 
Same effect using <code>ipairs()</code> Lua function (without initial state)
 
for k,v in ipairs(arr) do
 
  logf("%d:%d",k,v)
 
end
 
 
 
Now return to the most common example above using <code>pairs()</code> Lua function and read about <code>pairs()</code> and <code>ipairs()</code> implementation [https://www.lua.org/pil/7.3.html here].
 

Latest revision as of 18:01, 11 July 2019