lua

lua 筆記

lua 安裝
1
2
3
4
5
curl -R -O http://www.lua.org/ftp/lua-5.3.3.tar.gz
tar zxf lua-5.3.3.tar.gz
cd lua-5.3.3
# aix bsd c89 freebsd generic linux macosx mingw posix solaris
make macosx install

Load Lib

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
yume = require('yume')                -- load lib then cache & run
yume = dofile("lib1.lua") -- reload lib & run
yumeFunction = loadfile('yume.lua') -- load lib as function
yume = yumeFunction()

--[[
require 'luasocket'
no field package.preload['luasocket']
no file './luasocket.lua'
no file '/usr/local/share/lua/5.1/luasocket.lua'
no file '/usr/local/share/lua/5.1/luasocket/init.lua'
no file '/usr/local/lib/lua/5.1/luasocket.lua'
no file '/usr/local/lib/lua/5.1/luasocket/init.lua'
no file './luasocket.so'
no file '/usr/local/lib/lua/5.1/luasocket.so'
no file '/usr/local/lib/lua/5.1/loadall.so
]]--

Function

1
2
function f(x) return x * x end
f = function (x) return x * x end

?:

1
2
3
4
5
6
-- a ? b : c
a and b or c

-- 解釋
a and b -- b
nil or c -- c

for

index
1
for i = startIndex, endIndex, step do doX() end
table as dict
1
2
3
4
5
6
7
8
9
function pairs (t)
return next, t, nil
end

for k, v in next, t do
doX()
end

for key, val in pairs(u) do doX() end
table as array
1
for i, v in ipairs(a) do doX() end
Iterator
1
2
3
4
5
6
7
8
9
10
11
function list_iter (t)
local i = 0
local n = table.getn(t)
return
function ()
i = i + 1
if i <= n then return t[i] end
end
end

for element in list_iter(t) do doX() end
1
2
3
4
5
6
7
8
9
10
11
12
13
-- for var_1, ..., var_n in explist do block end
for v1,v2,v3,vn in interatorFunction,firstArgumentInitialResult,secondArgumentStartIndex do func() end

function yume_next (array,index)
local _index = index and index + 1 or 1
local _value = array[_index]
if not _value then return end
return _index,_value
end

for i,v in yume_next, {1,2,3}, 1 do func() end
for i,v in yume_next, {1,2,3}, nil do func() end
for i,v in yume_next, {1,2,3} do func() end

特殊呼叫方式

1
2
3
4
5
6
-- 單一 String 參數
print 'hello'

-- 單一 Table 參數
function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'} -- Prints 'Sonmi~451'.

全域變數

不需事先宣告,清空方式只需丟入 nil 即可。

1
2
3
4
5
print(b)  --> nil
b = 10
print(b) --> 10
b = nil
print(b) --> nil
1
2
3
4
-- 統管所有全域變數的特殊 Table
_G == _G._G
yume = 123
yume == _G.yume

註解

comments
1
2
3
4
5
6
7
8
--[[
print(10) --> 10
--]]


-- 多加上一個 '-' 即可取消多行註解
---[[
print(10) --> 10
--]]

自製 lib (需要用 local 區分全域變數,以免污染全域變數)

VeryNginxlink
1
2
3
4
5
6
7
8
9
local yume = {}

dream = 'dream' -- 會跟著被 require 進入到全域變數內

function yume.dream ()
print 'dream'
end

return yume
codeclink
1
2
3
4
local function abc do print'x' end
return {
abc = abc
}

Terminal

Before it starts running arguments, lua looks for an environment variable called LUA_INIT. If there is such a variable and its content is @filename, then lua loads the given file. If LUA_INIT is defined but does not start with `@´, then lua assumes that it contains Lua code and runs it. This variable gives you great power when configuring the stand-alone interpreter, because you have the full power of Lua in the configuration. You can pre-load packages, change the prompt and the path, define your own functions, rename or delete functions, and so on.

1
2
3
4
5
prompt> lua -e "print(math.sin(12))"   --> -0.53657291800043
# prompt> lua -i -l a.lua -e "x = 10"
prompt> lua -i -e "_PROMPT=' lua> '"
# prompt> lua script a b c
# prompt> lua -e "sin=math.sin" script a b

Type

lua 基本類型 :

  • nil (if 判斷時,只有 nil 以及 false 會被斷定為否,其他都為真{1, '', true ...})
  • boolean true | false
  • number double(0.3e12, 5e+20)
  • string (‘a’,”b”,[[c]]), (字串串接 ..)
  • userdata
  • function
  • thread
  • table
    1
    2
    3
    4
    5
    6
    7
    8
    a = {}
    a["yume"] = "dream"
    a["yume"] == a.yume

    days = {"Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday"}
    days[1] == "Sunday" -- 陣列從 1 開始
    w = {x=0, y=0, label="console"}
1
2
3
4
5
6
7
8
9
10
print(type("Hello world"))  --> string
print(type(10.4*3)) --> number

print(type(a)) --> nil (`a' is not initialized)
a = 10
print(type(a)) --> number
a = "a string!!"
print(type(a)) --> string
a = print -- yes, this is valid!
a(type(a)) --> function

Metatable & Metafunction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal
-- __add(a, b) for a + b
-- __sub(a, b) for a - b
-- __mul(a, b) for a * b
-- __div(a, b) for a / b
-- __mod(a, b) for a % b
-- __pow(a, b) for a ^ b
-- __unm(a) for -a
-- __concat(a, b) for a .. b
-- __len(a) for #a
-- __eq(a, b) for a == b
-- __lt(a, b) for a < b
-- __le(a, b) for a <= b
-- __index(a, b) <fn or a table> for a.b
-- __newindex(a, b, c) for a.b = c
-- __call(a, ...) for a(...)

class

定義 class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Dog = {}

function Dog:new()
newObj = {sound = 'woof'}
self.__index = self
return setmetatable(newObj, self)
end

function Dog:makeSound()
print('I say ' .. self.sound)
end

mrDog = Dog:new()
mrDog:makeSound()
class 繼承
1
2
3
4
5
6
7
8
9
LoudDog = Dog:new()

function LoudDog:makeSound()
s = self.sound .. ' '
print(s .. s .. s)
end

seymour = LoudDog:new()
seymour:makeSound()

???

1
2
# https://www.lua.org/pil/1.1.html
lua -la -lb

local P = {} – package
if _REQUIREDNAME == nil then
complex = P
else
_G[_REQUIREDNAME] = P
end
setfenv(1, P)

教學

Lua package manager

install luasocket
1
2
3
4
5
6
7
8
9
10
11
12
wget http://luarocks.github.io/luarocks/releases/luarocks-2.4.1.tar.gz
tar zxvf luarocks-2.4.1.tar.gz
cd luarocks-2.4.1
./configure
make build
make install

luarocks install luasocket
lua
> socket = require('socket')

luarocks remove --force luasocket

lua & c

yume2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

static int hello_c (lua_State *L) {
const char * from_lua = lua_tostring(L,1);
printf("Lua: %s\n",from_lua);
lua_pushstring(L,"Hi Lua, nice to meet you");
return 1;
}
static const struct luaL_Reg mylualib [] = {
{"hello_c", hello_c},
{NULL, NULL} /* sentinel */
};
int luaopen_yume2 (lua_State *L) {
luaL_openlib(L, "yume2", mylualib, 0);
lua_pushvalue(L, -1);
lua_setglobal(L, "yume2"); /* the module name */

return 1;
}
debian
1
2
3
4
gcc -c -fPIC -I /usr/include/lua5.1/yume2.c 
gcc yume2.o -shared -o yume2.so
# gcc -shared -o libhello.so -fPIC hello.c
# http://stackoverflow.com/questions/14884126/build-so-file-from-c-file-using-gcc-command-line
mac
1
2
3
gcc -v
# InstalledDir: /Applications/Xcode8_1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
gcc -c yume2.c ; gcc -O2 -bundle -undefined dynamic_lookup -o yume2.so yume2.o
lua call c
1
2
y = require 'yume2'
y.hello_c("hello")

和我一起写lua - Mac OS X环境编译C模块