1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | -- Overload the add operation -- to do string concatenation -- mt = {} function String(string) return setmetatable({value = string or ''}, mt) end -- The first operand is a String table -- The second operand is a string -- .. is the Lua concatenate operator -- function mt.__add(a, b) return String(a.value..b) end s = String('Hello') print((s + ' There ' + ' World!').value ) |
1 | Hello There World! |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | -- code courtesy of Rici Lake, rici@ricilake.net function Memoize(func, t) return setmetatable( t or {}, {__index = function(t, k) local v = func(k); t[k] = v; return v; end } ) end COLORS = {"red", "blue", "green", "yellow", "black"} color = Memoize( function(node) return COLORS[math.random(1, table.getn(COLORS))] end ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 1 #include <stdio.h> 2 #include <lua.h> 3 #include <lauxlib.h> 4 #include <lualib.h> 5 6 int main (void) { 7 char buff[256]; 8 int error; 9 lua_State *L = lua_open(); /* opens Lua */ 10 luaopen_base(L); /* opens the basic library */ 11 luaopen_table(L); /* opens the table library */ 12 luaopen_io(L); /* opens the I/O library */ 13 luaopen_string(L); /* opens the string lib. */ 14 luaopen_math(L); /* opens the math lib. */ 15 16 while (fgets(buff, sizeof(buff), stdin) != NULL) { 17 error = luaL_loadbuffer(L, buff, strlen(buff), "line") || 18 lua_pcall(L, 0, 0, 0); 19 if (error) { 20 fprintf(stderr, "%s", lua_tostring(L, -1)); 21 lua_pop(L, 1); /* pop error message from the stack */ 22 } 23 } 24 25 lua_close(L); 26 return 0; 27 } |
1 2 3 4 5 6 7 8 9 10 | .. if (luaL_loadfile(L, filename) || lua_pcall(L, 0, 0, 0)) error(L, "cannot run configuration file: %s", lua_tostring(L, -1)); lua_getglobal(L, "width"); lua_getglobal(L, "height"); .. width = (int) lua_tonumber(L, -2); height = (int) lua_tonumber(L, -1); .. |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |