nil :它是一个类型且只有一个值nil.它的主要功能是区别于其他任何值.如果对一个全局变量赋值nil等同于删除它.
条件测试中: LUA把 零值(0) 和 空字符串("") 当为true.
Lua版本unpack():
function unpack(theTable, index)
index = index or 1;
if theTable[index] then
return theTable[index], unpack(theTable, index+1);
end;
end;
Lua版本iterator:
function iterator(theTable)
local i = 0;
return function()
i = i+1;
return theTable[i] end;
end;
tb = {10, 20, 30};
iter = iterator(tb);
while true do
local element = iter();
if element == nil then
break;
end;
print(element);
end;
output:
10
20
30
Lua范围for与iterator:
tb= {10, 20, 30};
function iterator(theTable)
local i = 0;
return function()
i = i + 1;
return theTable[i];
end;
end;
for value in iterator(tb) do
print(value);
end;
Lua版本具有复杂状态的iterator:
local iterator;
function allWords()
local state= {line = io.read(), pos = 1};
return iterator, state;
end;
function iterator(state)
while state.line do
local s, e = string.find(state.line, "%w+", state.pos);
if s then
state.pos = e + 1;
return string.sub(state.line, s, e);
else
state.line = io.read();
state.pos = 1;
end;
end;
return nil;
end;
local itr, sta = allWords();
print(itr(sta));
Lua版本协程:
function receive(prod) --接受数据.
local status, value = coroutine.resume(prod);
return value;
end;
function send(x) --发送数据.
coroutine.yield(x);
end;
function producer() --生产者
return coroutine.create(function()
while true do
local x = io.read();
send(x);
end
end)
end
function filter(prod) --过滤
return coroutine.create(function() --创建一个协程
for line = 1, math.huge do
local x = receive(prod);
x = string.format("%5d %s", line, x);
send(x);
end
end)
end
function consumer(prod)
while true do
local x = receive(prod)
io.write(x, "\n");
end
end
Lua版本协程iterator:
function permgen(array, size)
size = size or #array;
if size <= 1 then
coroutine.yield(array);
else
for i=1, size do
array[size], array[i] = array[i],array[size];
permgen(array, size-1);
array[size], array[i] = array[i],array[size];
end
end
end
function printResult(array)
for index, value in ipairs(array) do
io.write(array[index], " ");
end
io.write("\n");
end
function permutations(array)
local co = coroutine.create(function() permgen(array) end)
return function()
local code, result = coroutine.resume(co);
return result;
end
end
for value in permutations({1, 2, 3}) do
printResult(value);
end
© 著作权归作者所有