Lua学习笔记二

1: 无状态的迭代器
a = {"one", "two", "three"}
for i, v in ipairs(a) do
    print(i, v)
end

2: loadstring 总 是在全局环境中编译他的串。

local i = 0
f = loadstring("i = i + 1")
g = function () i = i + 1 end

f() -->  a nil value
g()

这个例子中,和想象的一样 g 使用局部变量 i,然而 f 使用全局变量 i,但是没有全局的i,所以会报错

3: 创建N行M列的数组

mt = {} -- create the matrix
for i=1,N do
   mt[i] = {}    -- create a new row
   for j=1,M do
mt[i][j] = 0
end
end

4: co = coroutine.create(function ()
   print("hi")
end)
print(co)     --> thread: 0x8071d98

print(coroutine.status(co)) --> suspended

coroutine.resume(co) --> hi

print(coroutine.status(co)) --> dead

5: 打印在当前环境中所有的全局变量的名字:
for n in pairs(_G) do print(n) end


猜你喜欢

转载自7090.iteye.com/blog/1849652