文章目錄

loadfile

1
2
3
4
5
lua_State* L = luaL_newstate();
luaL_openlibs(L);

luaL_dofile(L, "xx.lua");
or luaL_loadfile(L, "xx.lua"); lua_pcall(L,0,0,0);

luaL_loadfile(L, “xx.lua”)之后一定要调用lua_pcall(L,0,0,0),否则读取不到脚本中的任何内容。luaL_loadfile生成一个匿名函数放在栈顶,当执行这个函数才会生成文件中的这些全局变量。

require

require和loadfile完成的功能相同,只有两点不同:1.require会搜索目录加载文件。2.require会避免加载同一个文件。搜索路径(?;?.lua;c:\windows\?;/usr/local/lua/?/?.lua)

local

1
2
3
4
local urllib = require "http.url"
local tostring = tostring
local pairs = pairs
local string = string

使用local可以避免全局变量的查找,提高效率

table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
lua_newtable(L);    /* creates a new table */
lua_pushinteger(L, 1);
lua_pushstring(L, "a");
lua_settable(L, -3); /* key[1] = "a" */
lua_pushinteger(L, 2);
lua_pushstring(L, "b");
lua_settable(L, -3); /* key[2] = "b" */
lua_setglobal(L,"key");

lua_getglobal(L,"key");
lua_pushinteger(L,1);
lua_gettable(L,-2);
const char* str=lua_tostring(L,-1);//a
lua_pop(L,1);
lua_pushinteger(L,2);
lua_gettable(L,-2);
str=lua_tostring(L,-1);//b
lua_pop(L,2);

文章目錄