Lua chapter 6

一个简单的迭代器示例

--迭代工厂函数

function value(t)

local i = 0;

return

function()

i = i+1;

return t[i];

end;

end;

t = {10,20,30};

iter = value(t);

while true do

local element = iter();

if element == nil  then

break;

end;

print("Element: " .. element);

end;

print();

--  另一种写法

for element in value(t) do

print("Element: " .. element);

end;

2、输出所有单词

function allword()

local line = io.read();

local pos = 1;

return

function()

local s, e = string.find(line, "%w+", pos);

if s then

pos = e + 1;

return string.sub(line, s, e);

end;

end;

end;

for word in allword() do

print(word);

end;

Lua chapter 6

时间: 2024-08-02 15:14:38

Lua chapter 6的相关文章

Lua chapter 2

1.算术运算符: "^"表示指数,"%"求模 如: print(9^0.5);        --> 表示9的平方根 x = 3.14567; print(x%1);     --> 获取小数部分 print(x - x%1);      --> 获取整数部分 print(x - x%0.01);   --> 获取精确到小数点后两位的结果,没有做四舍五入处理 2.关系运算符,对于table,userdata,函数,Lua做引用比较,只有当它们

Lua chapter 5

1.函数是一种 "第一类值" a = {p = print}; a.p("hello"); a = print; a("Hi"); 2. table 提供的函数 table.sort network = { {name = "lua", IP = "192.168.1.1"}, {name = "CPP", IP = "192.168.1.2"} }; for i,v

Lua chapter 3

1. 交换两个数值 x, y = y, x;   //等价于 x = y, y =x; 2. 变量初始化问题 a, b, c = 0; print(a,b,c);   --> 0  nil  nil 仅对第一个值复制,所以要初始化一组变量,应该提供多个初始值 a, b, c = 0, 0, 0; print(a, b, c);  --> 0   0   0 3. "尽可能地使用局部变量",这是一种良好的编程风格, 1)访问局部变量比全局更快 2)局部变量随作用域结束而消失,

Lua chapter 4

1. 函数可以返回多个值 return a, b, c; 但是如果函数不是作为表达式的最后一个元素的话,仅返回第一个 如: function f2() return "a", "b" end; x, y = f2()     -> x = "a", y = "b"; x, y = f2(), 1  -> x = "a", y = nil; 2. 可以将一个函数调用放入一对圆括号中,从而迫使它只返

Lua chapter 8 协同程序

1.协同程序,一个具有多个协同程序的程序在任意时刻,只能运行一个协同程序, 只有正在运行的协同程序被挂起时,它的执行才会暂停. 创建 co = coroutine.create(匿名函数);   -- 匿名函数就是线程要执行的东东 状态 coroutine.status(co); 唤醒 coroutine.resume(co); 挂起 coroutine.yield(); 2.yield-resume 数据交换 function f(a,b) coroutine.yield(a*10,b*10)

Lua chapter 1

1. 调用其他的.lua文件   dofile("xx.lua"); 2. 避免用 "_VERSION"这类的标识符,Lua将这类标识符用作特殊用途,通常保留"_"作为"哑变量" 3. Lua的一些保留字: do in local nil until 等 4. 注释:-- 表示行注释   --[[ ... ]] 表示块注释 一般的块注释这样写: --[[ print("for test"); --]] 这样

calling c++ function from Lua, implement sleep function

http://blog.csdn.net/cnjet/article/details/5909548 You can’t call c function directly from Lua, you have to create a wrapper function that allows calling from Lua. In this post, shows a simple example to implement millisecond sleep function to Lua us

用Lua写Wireshark插件

Create Wireshark Dissector by Lua 东方瀞[email protected] 1. Why Wireshark dissector Wireshark supports thousands of protocols now. But there are still some new protocols not supported and private protocols are not either. Fortunately, we can write diss

[译] Lua中的闭包

原文:(PDF) Lua中的闭包 摘要 第一类(first-class)函数是一种非常强大的语言结构,并且是函数式语言的基础特性.少数过程式语言由于其基于栈的实现,也支持第一类函数.本文讨论了Lua 5.x用于实现第一类函数的新算法.与之前所使用的技术不同,该算法不需要对源代码做静态分析(一种会极大降低Lua代码生成器即时性的技术)并且可支持使用顺序栈存储常规局部变量. 1 介绍 第一类函数是函数式语言的标志性特征,在过程式语言中也是很实用的概念.很多过程式函数如果以高阶函数的形式编写则会增加可