void PutWStrToArray(lua_State *L, int key, const wchar_t* str, intptr_t numchars) { lua_pushinteger(L, key); push_utf8_string(L, str, numchars); lua_settable(L, -3); }
bool PushVariant(lua_State *pLuaState, Variant &variant, bool substituteNullables) { switch ((VariantType) variant) { case V_UNDEFINED: case V_NULL: { if (substituteNullables) lua_pushstring(pLuaState, VAR_NULL_VALUE); else lua_pushnil(pLuaState); return true; break; } case V_STRING: { lua_pushstring(pLuaState, STR(variant)); return true; break; } case V_INT8: case V_INT16: case V_INT32: case V_INT64: case V_UINT8: case V_UINT16: case V_UINT32: case V_UINT64: case V_DOUBLE: { lua_pushnumber(pLuaState, (double) variant); return true; break; } case V_BOOL: { lua_pushboolean(pLuaState, (bool)variant); return true; break; } case V_TIMESTAMP: { struct tm tempTm = (struct tm) variant; lua_createtable(pLuaState, 0, 0); lua_pushstring(pLuaState, VAR_TYPE); lua_pushstring(pLuaState, VAR_TIMESTAMP); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_YEAR); lua_pushnumber(pLuaState, tempTm.tm_year + 1900); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_MONTH); lua_pushnumber(pLuaState, tempTm.tm_mon); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_DAY); lua_pushnumber(pLuaState, tempTm.tm_mday); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_HOUR); lua_pushnumber(pLuaState, tempTm.tm_hour); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_MIN); lua_pushnumber(pLuaState, tempTm.tm_min); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_SEC); lua_pushnumber(pLuaState, tempTm.tm_sec); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_ISDST); lua_pushboolean(pLuaState, false); lua_settable(pLuaState, -3); return true; break; } case V_DATE: { struct tm tempTm = (struct tm) variant; lua_createtable(pLuaState, 0, 0); lua_pushstring(pLuaState, VAR_TYPE); lua_pushstring(pLuaState, VAR_DATE); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_YEAR); lua_pushnumber(pLuaState, tempTm.tm_year + 1900); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_MONTH); lua_pushnumber(pLuaState, tempTm.tm_mon); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_DAY); lua_pushnumber(pLuaState, tempTm.tm_mday); lua_settable(pLuaState, -3); return true; break; } case V_TIME: { struct tm tempTm = (struct tm) variant; lua_createtable(pLuaState, 0, 0); lua_pushstring(pLuaState, VAR_TYPE); lua_pushstring(pLuaState, VAR_TIME); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_YEAR); lua_pushnumber(pLuaState, 1970); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_MONTH); lua_pushnumber(pLuaState, 1); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_DAY); lua_pushnumber(pLuaState, 1); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_HOUR); lua_pushnumber(pLuaState, tempTm.tm_hour); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_MIN); lua_pushnumber(pLuaState, tempTm.tm_min); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_SEC); lua_pushnumber(pLuaState, tempTm.tm_sec); lua_settable(pLuaState, -3); lua_pushstring(pLuaState, VAR_ISDST); lua_pushboolean(pLuaState, false); lua_settable(pLuaState, -3); return true; break; } case V_TYPED_MAP: case V_MAP: { lua_createtable(pLuaState, 0, 0); if ((VariantType) variant == V_TYPED_MAP) { lua_pushstring(pLuaState, VAR_MAP_NAME); lua_pushstring(pLuaState, STR(variant.GetTypeName())); lua_settable(pLuaState, -3); } FOR_MAP(variant, string, Variant, i) { if (MAP_KEY(i).find(VAR_INDEX_VALUE) == 0) { string temp = MAP_KEY(i).substr(VAR_INDEX_VALUE_LEN, string::npos); char *error = NULL; double index = strtod(STR(temp), &error); if (error == STR(temp) + temp.size()) { lua_pushnumber(pLuaState, index); } else { lua_pushstring(pLuaState, STR(MAP_KEY(i))); } } else { lua_pushstring(pLuaState, STR(MAP_KEY(i))); } if (!PushVariant(pLuaState, MAP_VAL(i), true)) { FINEST("Unable to push primitive"); return false; } lua_settable(pLuaState, -3); } return true; break; } default: { FATAL("Unknown type %hhu", (VariantType) variant); return false; break; } } return true; }
/* *** */ int register_lua_globals(struct CONTEXT *context) { int i, error = 0; /* add standard libs */ luaL_openlibs(context->lua); /* add specific functions */ lua_register(context->lua, L_FUNCTION_PREFIX"add_job", lf_add_job); lua_register(context->lua, L_FUNCTION_PREFIX"add_output", lf_add_output); lua_register(context->lua, L_FUNCTION_PREFIX"add_pseudo", lf_add_pseudo); lua_register(context->lua, L_FUNCTION_PREFIX"add_dependency", lf_add_dependency); lua_register(context->lua, L_FUNCTION_PREFIX"add_constraint_shared", lf_add_constraint_shared); lua_register(context->lua, L_FUNCTION_PREFIX"add_constraint_exclusive", lf_add_constraint_exclusive); lua_register(context->lua, L_FUNCTION_PREFIX"default_target", lf_default_target); lua_register(context->lua, L_FUNCTION_PREFIX"set_touch", lf_set_touch); lua_register(context->lua, L_FUNCTION_PREFIX"set_filter", lf_set_filter); /* advanced dependency checkers */ lua_register(context->lua, L_FUNCTION_PREFIX"add_dependency_cpp_set_paths", lf_add_dependency_cpp_set_paths); lua_register(context->lua, L_FUNCTION_PREFIX"add_dependency_cpp", lf_add_dependency_cpp); lua_register(context->lua, L_FUNCTION_PREFIX"add_dependency_search", lf_add_dependency_search); /* path manipulation */ lua_register(context->lua, L_FUNCTION_PREFIX"path_join", lf_path_join); lua_register(context->lua, L_FUNCTION_PREFIX"path_normalize", lf_path_normalize); lua_register(context->lua, L_FUNCTION_PREFIX"path_isnice", lf_path_isnice); lua_register(context->lua, L_FUNCTION_PREFIX"path_ext", lf_path_ext); lua_register(context->lua, L_FUNCTION_PREFIX"path_dir", lf_path_dir); lua_register(context->lua, L_FUNCTION_PREFIX"path_base", lf_path_base); lua_register(context->lua, L_FUNCTION_PREFIX"path_filename", lf_path_filename); /* various support functions */ lua_register(context->lua, L_FUNCTION_PREFIX"collect", lf_collect); lua_register(context->lua, L_FUNCTION_PREFIX"collectrecursive", lf_collectrecursive); lua_register(context->lua, L_FUNCTION_PREFIX"collectdirs", lf_collectdirs); lua_register(context->lua, L_FUNCTION_PREFIX"collectdirsrecursive", lf_collectdirsrecursive); lua_register(context->lua, L_FUNCTION_PREFIX"listdir", lf_listdir); lua_register(context->lua, L_FUNCTION_PREFIX"update_globalstamp", lf_update_globalstamp); lua_register(context->lua, L_FUNCTION_PREFIX"loadfile", lf_loadfile); lua_register(context->lua, L_FUNCTION_PREFIX"load_plugin", lf_loadplugin); lua_register(context->lua, L_FUNCTION_PREFIX"mkdir", lf_mkdir); lua_register(context->lua, L_FUNCTION_PREFIX"fileexist", lf_fileexist); lua_register(context->lua, L_FUNCTION_PREFIX"isstring", lf_isstring); lua_register(context->lua, L_FUNCTION_PREFIX"istable", lf_istable); lua_register(context->lua, L_FUNCTION_PREFIX"table_walk", lf_table_walk); lua_register(context->lua, L_FUNCTION_PREFIX"table_deepcopy", lf_table_deepcopy); lua_register(context->lua, L_FUNCTION_PREFIX"table_tostring", lf_table_tostring); lua_register(context->lua, L_FUNCTION_PREFIX"table_flatten", lf_table_flatten); /* error handling */ lua_register(context->lua, "errorfunc", lf_errorfunc); /* create arguments table */ lua_pushstring(context->lua, CONTEXT_LUA_SCRIPTARGS_TABLE); lua_newtable(context->lua); for(i = 0; i < option_num_scriptargs; i++) { const char *separator = option_scriptargs[i]; while(*separator != '=') separator++; lua_pushlstring(context->lua, option_scriptargs[i], separator-option_scriptargs[i]); lua_pushstring(context->lua, separator+1); lua_settable(context->lua, -3); } lua_settable(context->lua, LUA_GLOBALSINDEX); /* create targets table */ lua_pushstring(context->lua, CONTEXT_LUA_TARGETS_TABLE); lua_newtable(context->lua); for(i = 0; i < option_num_targets; i++) { lua_pushstring(context->lua, option_targets[i]); lua_rawseti(context->lua, -2, i); } lua_settable(context->lua, LUA_GLOBALSINDEX); /* set paths */ { char cwd[MAX_PATH_LENGTH]; if(!getcwd(cwd, sizeof(cwd))) { printf("%s: error: couldn't get current working directory\n", session.name); return -1; } lua_setglobalstring(context->lua, CONTEXT_LUA_PATH, context->script_directory); lua_setglobalstring(context->lua, CONTEXT_LUA_WORKPATH, cwd); } /* set version, family, platform, arch, verbocity */ lua_setglobalstring(context->lua, "_bam_version", BAM_VERSION_STRING); lua_setglobalstring(context->lua, "_bam_version_complete", BAM_VERSION_STRING_COMPLETE); lua_setglobalstring(context->lua, "family", BAM_FAMILY_STRING); lua_setglobalstring(context->lua, "platform", BAM_PLATFORM_STRING); lua_setglobalstring(context->lua, "arch", BAM_ARCH_STRING); lua_setglobalstring(context->lua, "_bam_exe", session.exe); lua_pushnumber(context->lua, session.verbose); lua_setglobal(context->lua, "verbose"); if(option_debug_trace_vm) lua_sethook(context->lua, lua_vm_trace_hook, LUA_MASKCOUNT, 1); /* load base script */ if(!option_debug_nointernal) { int ret; const char *p; int f; for(f = 0; internal_files[f].filename; f++) { p = internal_files[f].content; if(session.verbose) printf("%s: reading internal file '%s'\n", session.name, internal_files[f].filename); lua_getglobal(context->lua, "errorfunc"); /* push error function to stack */ ret = lua_load(context->lua, internal_base_reader, (void *)&p, internal_files[f].filename); if(ret != 0) { lf_errorfunc(context->lua); if(ret == LUA_ERRSYNTAX) { } else if(ret == LUA_ERRMEM) printf("%s: memory allocation error\n", session.name); else printf("%s: unknown error parsing base script\n", session.name); error = 1; } else if(lua_pcall(context->lua, 0, LUA_MULTRET, -2) != 0) error = 1; } } return error; }
static void luaT_info_end_table(struct info_handler *info) { lua_State *L = (lua_State *) info->ctx; lua_settable(L, -3); }
static int vlclua_del_callback( lua_State *L ) { vlclua_callback_t *p_callback; bool b_found = false; vlc_object_t **pp_obj = luaL_checkudata( L, 1, "vlc_object" ); const char *psz_var = luaL_checkstring( L, 2 ); lua_settop( L, 4 ); /* makes sure that optional data arg is set */ if( !lua_isfunction( L, 3 ) ) return vlclua_error( L ); /* obj var func data */ lua_getglobal( L, "vlc" ); /* obj var func data vlc */ lua_getfield( L, -1, "callbacks" ); if( lua_isnil( L, -1 ) ) return luaL_error( L, "Couldn't find matching callback." ); /* obj var func data vlc callbacks */ lua_remove( L, -2 ); /* obj var func data callbacks */ lua_pushnil( L ); /* obj var func data callbacks index */ while( lua_next( L, -2 ) ) { /* obj var func data callbacks index value */ if( lua_isnumber( L, -2 ) ) { lua_getfield( L, -1, "private2" ); /* obj var func data callbacks index value private2 */ if( lua_equal( L, 2, -1 ) ) /* var name is equal */ { lua_pop( L, 1 ); /* obj var func data callbacks index value */ lua_getfield( L, -1, "callback" ); /* obj var func data callbacks index value callback */ if( lua_equal( L, 3, -1 ) ) /* callback function is equal */ { lua_pop( L, 1 ); /* obj var func data callbacks index value */ lua_getfield( L, -1, "data" ); /* callback data is equal */ /* obj var func data callbacks index value data */ if( lua_equal( L, 4, -1 ) ) { vlc_object_t *p_obj2; lua_pop( L, 1 ); /* obj var func data callbacks index value */ lua_getfield( L, -1, "private1" ); /* obj var func data callbacks index value private1 */ p_obj2 = (vlc_object_t*)luaL_checklightuserdata( L, -1 ); if( p_obj2 == *pp_obj ) /* object is equal */ { lua_pop( L, 1 ); /* obj var func data callbacks index value */ lua_getfield( L, -1, "private3" ); /* obj var func data callbacks index value private3 */ p_callback = (vlclua_callback_t*)luaL_checklightuserdata( L, -1 ); lua_pop( L, 2 ); /* obj var func data callbacks index */ b_found = true; break; } else { /* obj var func data callbacks index value private1 */ lua_pop( L, 1 ); /* obj var func data callbacks index value */ } } else { /* obj var func data callbacks index value data */ lua_pop( L, 1 ); /* obj var func data callbacks index value */ } } else { /* obj var func data callbacks index value callback */ lua_pop( L, 1 ); /* obj var func data callbacks index value */ } } else { /* obj var func data callbacks index value private2 */ lua_pop( L, 1 ); /* obj var func data callbacks index value */ } } /* obj var func data callbacks index value */ lua_pop( L, 1 ); /* obj var func data callbacks index */ } if( b_found == false ) /* obj var func data callbacks */ return luaL_error( L, "Couldn't find matching callback." ); /* else */ /* obj var func data callbacks index*/ var_DelCallback( *pp_obj, psz_var, vlclua_callback, p_callback ); free( p_callback ); /* obj var func data callbacks index */ lua_pushnil( L ); /* obj var func data callbacks index nil */ lua_settable( L, -3 ); /* delete the callback table entry */ /* obj var func data callbacks */ lua_pop( L, 5 ); /* <empty stack> */ return 0; }
inline void libsox_(TableNum)(lua_State *L, char *key, lua_Number val) { lua_pushstring(L, key); lua_pushnumber(L, val); lua_settable(L, -3); }
static void storestring(lua_State *L, const char *name, const char *value) { lua_pushstring(L, name); lua_pushstring(L, value); lua_settable(L, -3); }
static int buffer_readobject(lua_State *L, const char *data, size_t pos, size_t size, struct reader_t *R) { int op; luaL_check(pos < size, "readobject overflow"); op = data[pos++]; switch(op & 0x0f) { case OP_NIL: lua_pushnil(L); break; case OP_TRUE: lua_pushboolean(L, 1); break; case OP_FALSE: lua_pushboolean(L, 0); break; case OP_ZERO: lua_pushnumber(L, 0); break; case OP_INT: { int len = (op & 0xf0) >> 4; lua_Integer n = 0; luaL_check(pos + len <= size, "read int overflow"); memcpy(&n, data + pos, len); correctbytes(&n, len); lua_pushnumber(L, n); pos += len; break; } case OP_FLOAT: { int len = (op & 0xf0) >> 4; luaL_check(pos + len <= size, "read float or double overflow"); if (len == sizeof(float)) { float n = 0; memcpy(&n, data + pos, len); correctbytes(&n, len); lua_pushnumber(L, n); } else { double n = 0; memcpy(&n, data + pos, len); correctbytes(&n, len); lua_pushnumber(L, n); } pos += len; break; } case OP_STRING: { int len = (op & 0xf0) >> 4; size_t n = 0; luaL_check(pos + len <= size, "read string overflow"); memcpy(&n, data + pos, len); correctbytes(&n, len); pos += len; luaL_check(pos + n <= size, "read string overflow"); lua_pushlstring(L, data + pos, n); pos += n; break; } case OP_TABLE: { size_t i; lua_newtable(L); lua_pushvalue(L, -1); luaL_check(R->count < REFS_SIZE, "table refs overflow %d", REFS_SIZE); R->refs[R->count].pos = pos - R->pos - 1; R->refs[R->count++].idx = luaL_ref(L, LUA_REGISTRYINDEX); for (i = 1; data[pos] != OP_TABLE_DELIMITER; ++i) { pos = buffer_readobject(L, data, pos, size, R); lua_rawseti(L, -2, i); } pos++; while (data[pos] != OP_TABLE_END) { pos = buffer_readobject(L, data, pos, size, R); pos = buffer_readobject(L, data, pos, size, R); lua_settable(L, -3); } pos++; break; } case OP_TABLE_REF: { size_t i, where = data[pos++]; for (i = 0; i < R->count; ++i) { if (R->refs[i].pos == where) { lua_rawgeti(L, LUA_REGISTRYINDEX, R->refs[i].idx); return pos; } } luaL_error(L, "bad ref: %d", where); return 0; } default: luaL_error(L, "bad opecode: %d", op); return 0; } return pos; }
LUALIB_API int luaopen_zlib(lua_State *L) { const luaL_Reg lzstream_meta[] = { {"write", lzstream_compress }, {"read", lzstream_decompress }, {"lines", lzstream_lines }, {"flush", lzstream_flush }, {"close", lzstream_close }, {"adler", lzstream_adler }, {"__tostring", lzstream_tostring }, {"__gc", lzstream_gc }, {NULL, NULL} }; const luaL_Reg zlib[] = { {"version", lzlib_version }, {"adler32", lzlib_adler32 }, {"crc32", lzlib_crc32 }, {"deflate", lzlib_deflate }, {"inflate", lzlib_inflate }, {"compress", lzlib_compress }, {"decompress", lzlib_decompress }, {NULL, NULL} }; /* ====================================================================== */ /* create new metatable for zlib compression structures */ luaL_newmetatable(L, ZSTREAMMETA); lua_pushliteral(L, "__index"); lua_pushvalue(L, -2); /* push metatable */ lua_rawset(L, -3); /* metatable.__index = metatable */ /* ** Stack: metatable */ #if LUA_VERSION_NUM >= 502 luaL_setfuncs(L, lzstream_meta, 0); #else luaL_register(L, NULL, lzstream_meta); #endif lua_pop(L, 1); /* remove metatable from stack */ /* ** Stack: */ lua_newtable(L); lua_pushliteral (L, "_COPYRIGHT"); lua_pushliteral (L, "Copyright (C) 2003-2010 Tiago Dionizio"); lua_settable (L, -3); lua_pushliteral (L, "_DESCRIPTION"); lua_pushliteral (L, "Lua 5 interface to access zlib library functions"); lua_settable (L, -3); lua_pushliteral (L, "_VERSION"); lua_pushliteral (L, "lzlib 0.4-work3"); lua_settable (L, -3); #define PUSH_LITERAL(name) \ lua_pushliteral (L, #name); \ lua_pushinteger (L, Z_##name); \ lua_settable (L, -3); #define PUSH_NUMBER(name, value) \ lua_pushliteral (L, #name); \ lua_pushinteger (L, value); \ lua_settable (L, -3); PUSH_LITERAL(NO_COMPRESSION) PUSH_LITERAL(BEST_SPEED) PUSH_LITERAL(BEST_COMPRESSION) PUSH_LITERAL(DEFAULT_COMPRESSION) PUSH_LITERAL(FILTERED) PUSH_LITERAL(HUFFMAN_ONLY) PUSH_LITERAL(RLE) PUSH_LITERAL(FIXED) PUSH_LITERAL(DEFAULT_STRATEGY) PUSH_NUMBER(MINIMUM_MEMLEVEL, 1) PUSH_NUMBER(MAXIMUM_MEMLEVEL, 9) PUSH_NUMBER(DEFAULT_MEMLEVEL, 8) PUSH_NUMBER(DEFAULT_WINDOWBITS, 15) PUSH_NUMBER(MINIMUM_WINDOWBITS, 8) PUSH_NUMBER(MAXIMUM_WINDOWBITS, 15) PUSH_NUMBER(GZIP_WINDOWBITS, 16) PUSH_NUMBER(RAW_WINDOWBITS, -1) #if LUA_VERSION_NUM >= 502 luaL_setfuncs(L, zlib, 0); #else luaL_register(L, NULL, zlib); #endif /* ** Stack: zlib table */ return 1; }
void sb_lua_set_context(lua_State *L, sb_lua_ctxt_t *ctxt) { lua_pushlightuserdata(L, (void *)&sb_lua_ctxt_key); lua_pushlightuserdata(L, (void *)ctxt); lua_settable(L, LUA_REGISTRYINDEX); }
/* parse url encoded strings into two tables and pushes them into the stack */ void mk_lua_urlencoded_to_table(lua_State *L, char *qs) { char *key; char *value; char *strtok_state; int t; key = strtok_r(qs, "&", &strtok_state); while (key) { value = strchr(key, '='); if (value) { *value = '\0'; /* Split the string in two */ value++; /* Skip passed the = */ } else { value = "1"; } /* store the key and values into tables */ lua_getfield(L, -1, key); /* [VALUE, table<s,t>, table<s,s>] */ /* borrowed from apache mod_lua */ t = lua_type(L, -1); switch (t) { case LUA_TNIL: case LUA_TNONE:{ lua_pop(L, 1); /* [table<s,t>, table<s,s>] */ lua_newtable(L); /* [array, table<s,t>, table<s,s>] */ lua_pushnumber(L, 1); /* [1, array, table<s,t>, table<s,s>] */ lua_pushstring(L, value); /* [string, 1, array, table<s,t>, table<s,s>] */ lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */ lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */ break; } case LUA_TTABLE:{ /* [array, table<s,t>, table<s,s>] */ int size = lua_rawlen(L, -1); lua_pushnumber(L, size + 1); /* [#, array, table<s,t>, table<s,s>] */ lua_pushstring(L, value); /* [string, #, array, table<s,t>, table<s,s>] */ lua_settable(L, -3); /* [array, table<s,t>, table<s,s>] */ lua_setfield(L, -2, key); /* [table<s,t>, table<s,s>] */ break; } } /* L is [table<s,t>, table<s,s>] */ /* build simple */ lua_getfield(L, -2, key); /* [VALUE, table<s,s>, table<s,t>] */ if (lua_isnoneornil(L, -1)) { /* only set if not already set */ lua_pop(L, 1); /* [table<s,s>, table<s,t>]] */ lua_pushstring(L, value); /* [string, table<s,s>, table<s,t>] */ lua_setfield(L, -3, key); /* [table<s,s>, table<s,t>] */ } else { lua_pop(L, 1); } key = strtok_r(NULL, "&", &strtok_state); } }
int face_from_options(lua_State* L) { FT_Face face; FcChar8 * font_path; FcPattern* p; FcPattern* matched; FcResult result; int index = 0; const char *family = "Gentium"; double pointSize = 12; int slant = FC_SLANT_ROMAN; int weight = 100; const char *script = "latin"; const char *language = "eng"; int direction = HB_DIRECTION_LTR; if (!lua_istable(L, 1)) return 0; lua_pushstring(L, "font"); lua_gettable(L, -2); if (lua_isstring(L, -1)) { family = lua_tostring(L, -1); } lua_pop(L,1); lua_pushstring(L, "weight"); lua_gettable(L, -2); if (lua_isnumber(L, -1)) { int newWeight = lua_tointeger(L, -1); if (newWeight <= 100) newWeight = FC_WEIGHT_THIN; else if (newWeight <= 200) newWeight = FC_WEIGHT_ULTRALIGHT; else if (newWeight <= 300) newWeight = FC_WEIGHT_LIGHT; else if (newWeight <= 400) newWeight = FC_WEIGHT_NORMAL; else if (newWeight <= 500) newWeight = FC_WEIGHT_MEDIUM; else if (newWeight <= 600) newWeight = FC_WEIGHT_DEMIBOLD; else if (newWeight <= 700) newWeight = FC_WEIGHT_BOLD; else if (newWeight <= 800) newWeight = FC_WEIGHT_ULTRABOLD; else newWeight = FC_WEIGHT_HEAVY; weight = newWeight; } lua_pop(L,1); lua_pushstring(L, "size"); lua_gettable(L, -2); if (lua_isnumber(L, -1)) { pointSize = lua_tonumber(L, -1); } lua_pop(L,1); lua_pushstring(L, "language"); lua_gettable(L, -2); if (lua_isstring(L, -1)) { language = lua_tostring(L, -1); } lua_pop(L,1); lua_pushstring(L, "style"); lua_gettable(L, -2); if (lua_isstring(L, -1)) { const char* newStyleAsText = lua_tostring(L, -1); if (!strcmp(newStyleAsText, "italic")) slant = FC_SLANT_ITALIC; } lua_pop(L,1); p = FcPatternCreate(); FcPatternAddString (p, FC_FAMILY, (FcChar8*)(family)); FcPatternAddDouble (p, FC_SIZE, pointSize); FcPatternAddInteger(p, FC_SLANT, slant); FcPatternAddInteger(p, FC_WEIGHT, weight); // /* Add fallback fonts here. Some of the standard 14 should be fine. */ FcPatternAddString (p, FC_FAMILY,(FcChar8*) "Times-Roman"); FcPatternAddString (p, FC_FAMILY,(FcChar8*) "Times"); FcPatternAddString (p, FC_FAMILY,(FcChar8*) "Helvetica"); matched = FcFontMatch (0, p, &result); if (FcPatternGetString (matched, FC_FILE, 0, &font_path) != FcResultMatch) return 0; FcPatternGetInteger(matched, FC_INDEX, 0, &index); font_path = (FcChar8 *)strdup((char*)font_path); /* XXX signedness problems? */ if (!font_path) { printf("Finding font path failed\n"); return 0; } /* Push back slant and weight, we need to pass them to libpdftex */ FcPatternGetInteger(matched, FC_SLANT, 0, &slant); FcPatternGetInteger(matched, FC_WEIGHT, 0, &weight); /* Find out which family we did actually pick up */ if (FcPatternGetString (matched, FC_FAMILY, 0, &family) != FcResultMatch) return 0; lua_newtable(L); lua_pushstring(L, "filename"); lua_pushstring(L, (char*)font_path); lua_settable(L, -3); lua_pushstring(L, "family"); lua_pushstring(L, (char*)(family)); lua_settable(L, -3); FcPatternDestroy (matched); FcPatternDestroy (p); face = (FT_Face)malloc(sizeof(FT_Face)); if (FT_New_Face(ft_library, (char*)font_path, index, &face)) return 0; if (FT_Set_Char_Size(face,pointSize * 64.0, 0, 0, 0)) return 0; lua_pushstring(L, "index"); lua_pushinteger(L, index); lua_settable(L, -3); lua_pushstring(L, "pointsize"); lua_pushnumber(L, pointSize); lua_settable(L, -3); lua_pushstring(L, "face"); lua_pushlightuserdata(L, face); lua_settable(L, -3); return 1; }
int shape (lua_State *L) { const char * text = luaL_checkstring(L, 1); FT_Face face = lua_touserdata(L, 2); const char * script = luaL_checkstring(L, 3); const char * direction_s = luaL_checkstring(L, 4); const char * lang = luaL_checkstring(L, 5); double point_size = luaL_checknumber(L, 6); const char * featurestring = luaL_checkstring(L, 7); hb_segment_properties_t segment_props; hb_shape_plan_t *shape_plan; hb_direction_t direction; hb_feature_t* features; int nFeatures = 0; unsigned int glyph_count = 0; hb_font_t *hb_ft_font; hb_face_t *hb_ft_face; hb_buffer_t *buf; hb_glyph_info_t *glyph_info; hb_glyph_position_t *glyph_pos; unsigned int j; features = scan_feature_string(featurestring, &nFeatures); if (!strcasecmp(direction_s,"RTL")) direction = HB_DIRECTION_RTL; else if (!strcasecmp(direction_s,"TTB")) direction = HB_DIRECTION_TTB; else direction = HB_DIRECTION_LTR; hb_ft_font = hb_ft_font_create(face, NULL); hb_face_t* hbFace = hb_font_get_face(hb_ft_font); buf = hb_buffer_create(); hb_buffer_add_utf8(buf, text, strlen(text), 0, strlen(text)); hb_buffer_set_script(buf, hb_tag_from_string(script, strlen(script))); hb_buffer_set_direction(buf, direction); hb_buffer_set_language(buf, hb_language_from_string(lang,strlen(lang))); hb_buffer_guess_segment_properties(buf); hb_buffer_get_segment_properties(buf, &segment_props); shape_plan = hb_shape_plan_create_cached(hbFace, &segment_props, features, nFeatures, NULL); int res = hb_shape_plan_execute(shape_plan, hb_ft_font, buf, features, nFeatures); glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count); glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count); lua_checkstack(L, glyph_count); for (j = 0; j < glyph_count; ++j) { char namebuf[255]; box glyph_extents = { 0.0, 0.0, 0.0 }; calculate_extents(&glyph_extents, glyph_info[j], glyph_pos[j], face, point_size, direction); lua_newtable(L); lua_pushstring(L, "name"); FT_Get_Glyph_Name( face, glyph_info[j].codepoint, namebuf, 255 ); lua_pushstring(L, namebuf); lua_settable(L, -3); if (direction != HB_DIRECTION_TTB) { /* XXX */ if (glyph_pos[j].x_offset) { lua_pushstring(L, "x_offset"); lua_pushnumber(L, glyph_pos[j].x_offset / 64.0); lua_settable(L, -3); } if (glyph_pos[j].y_offset) { lua_pushstring(L, "y_offset"); lua_pushnumber(L, glyph_pos[j].y_offset / 64.0); lua_settable(L, -3); } } lua_pushstring(L, "codepoint"); lua_pushinteger(L, glyph_info[j].codepoint); lua_settable(L, -3); lua_pushstring(L, "width"); lua_pushnumber(L, glyph_extents.width); lua_settable(L, -3); lua_pushstring(L, "height"); lua_pushnumber(L, glyph_extents.height); lua_settable(L, -3); lua_pushstring(L, "depth"); lua_pushnumber(L, glyph_extents.depth); lua_settable(L, -3); } /* Cleanup */ hb_buffer_destroy(buf); hb_font_destroy(hb_ft_font); hb_shape_plan_destroy(shape_plan); free(features); return glyph_count; }
lua_State *new_lua_thread(lua_State *_L) { lua_State *L = NULL; if(lua_thread_head) { L = lua_thread_head->L; void *l = lua_thread_head; lua_thread_head = lua_thread_head->next; if(lua_thread_tail == l) { lua_thread_head = NULL; lua_thread_tail = NULL; } free(l); return L; } if(lua_thread_count >= MAX_LUA_THREAD_COUNT) { LOGF(ERR, "Lua thread pool full!"); return NULL; } lua_thread_count++; ///lua_getglobal(_L, "cothreads"); L = lua_newthread(_L); ///lua_rawseti(_L, -2, lua_thread_count); ///lua_pop(_L, 1); int m_refkey = luaL_ref(_L, LUA_REGISTRYINDEX); // when you want to kill it. //lua_unref(m_state, m_refkey); lua_createtable(L, 0, 100); lua_pushvalue(L, -1); lua_setfield(L, -2, "_G"); lua_newtable(L); lua_pushliteral(L, "__index"); lua_pushvalue(L, LUA_GLOBALSINDEX); lua_settable(L, -3); lua_pushcfunction(L, l_env_newindex); lua_setfield(L, -2, "__newindex"); lua_setmetatable(L, -2); lua_replace(L, LUA_GLOBALSINDEX); lua_getglobal(L, "__main"); lua_pushvalue(L, LUA_GLOBALSINDEX); lua_setfenv(L, -2); if(lua_resume(L, 0) == LUA_ERRRUN) { if(lua_isstring(L, -1)) { LOGF(ERR, "Lua:error %s", lua_tostring(L, -1)); } lua_pop(L, 1); } lua_createtable(L, 0, 100); lua_setglobal(L, "__INDEXS"); return L; }
/* | Allows user scripts to observe filedescriptors | | Params on Lua stack: | 1: file descriptor | 2: function to call when read becomes ready | 3: function to call when write becomes ready */ static int l_observe_fd( lua_State *L ) { int fd = luaL_checknumber( L, 1 ); bool ready = false; bool writey = false; // Stores the user function in the lua registry. // It uses the address of the cores ready/write functions // for the user as key if( !lua_isnoneornil( L, 2 ) ) { lua_pushlightuserdata( L, (void *) user_obs_ready ); lua_gettable( L, LUA_REGISTRYINDEX ); if( lua_isnil( L, -1 ) ) { lua_pop ( L, 1 ); lua_newtable ( L ); lua_pushlightuserdata ( L, (void *) user_obs_ready ); lua_pushvalue ( L, -2 ); lua_settable ( L, LUA_REGISTRYINDEX ); } lua_pushnumber ( L, fd ); lua_pushvalue ( L, 2 ); lua_settable ( L, -3 ); lua_pop ( L, 1 ); ready = true; } if( !lua_isnoneornil( L, 3 ) ) { lua_pushlightuserdata( L, (void *) user_obs_writey ); lua_gettable (L, LUA_REGISTRYINDEX ); if( lua_isnil(L, -1) ) { lua_pop ( L, 1 ); lua_newtable ( L ); lua_pushlightuserdata ( L, (void *) user_obs_writey ); lua_pushvalue ( L, -2 ); lua_settable ( L, LUA_REGISTRYINDEX ); } lua_pushnumber ( L, fd ); lua_pushvalue ( L, 3 ); lua_settable ( L, -3 ); lua_pop ( L, 1 ); writey = true; } // tells the core to watch the fd observe_fd( fd, ready ? user_obs_ready : NULL, writey ? user_obs_writey : NULL, user_obs_tidy, NULL ); return 0; }
static int getClass(lua_State *L) { const char *name = luaL_checkstring(L, 1); gnative_Class *cls = gnative_GetClass(name); if (cls == NULL) return 0; lua_pushlightuserdata(L, &keyClasses); lua_gettable(L, LUA_REGISTRYINDEX); lua_pushlightuserdata(L, cls); lua_gettable(L, -2); lua_remove(L, -2); if (!lua_isnil(L, -1)) return 1; lua_pop(L, 1); lua_newtable(L); lua_pushlightuserdata(L, cls); lua_setfield(L, -2, "__classdata"); lua_pushcfunction(L, __index); lua_setfield(L, -2, "__index"); lua_pushvalue(L, -1); lua_pushcclosure(L, __new, 1); lua_setfield(L, -2, "new"); lua_pushvalue(L, -1); lua_pushcclosure(L, addFunction, 1); lua_setfield(L, -2, "addFunction"); gnative_Class *superclass = gnative_ClassGetSuperclass(cls); if (superclass != NULL) { lua_pushcfunction(L, getClass); lua_pushstring(L, gnative_ClassGetName(superclass)); lua_call(L, 1, 1); lua_setmetatable(L, -2); } else { lua_pushlightuserdata(L, &keyObject); lua_gettable(L, LUA_REGISTRYINDEX); lua_setmetatable(L, -2); } lua_pushlightuserdata(L, &keyClasses); lua_gettable(L, LUA_REGISTRYINDEX); lua_pushlightuserdata(L, cls); lua_pushvalue(L, -3); lua_settable(L, -3); lua_pop(L, 1); return 1; }
/* | The effective main for one run. | | HUP signals may cause several runs of the one main. */ int main1( int argc, char *argv[] ) { // the Lua interpreter lua_State * L; // the runner file char * lsyncd_runner_file = NULL; int argp = 1; // load Lua L = luaL_newstate( ); luaL_openlibs( L ); { // checks the lua version const char * version; int major, minor; lua_getglobal( L, "_VERSION" ); version = luaL_checkstring( L, -1 ); if( sscanf( version, "Lua %d.%d", &major, &minor ) != 2 ) { fprintf( stderr, "cannot parse lua library version!\n" ); exit (-1 ); } if( major < 5 || (major == 5 && minor < 1) ) { fprintf( stderr, "Lua library is too old. Needs 5.1 at least" ); exit( -1 ); } lua_pop( L, 1 ); } { // logging is prepared quite early int i = 1; add_logcat( "Normal", LOG_NOTICE ); add_logcat( "Warn", LOG_WARNING ); add_logcat( "Error", LOG_ERR ); while( i < argc ) { if( strcmp( argv[ i ], "-log" ) && strcmp( argv[ i ], "--log" ) ) { // arg is neither -log or --log i++; continue; } if( ++i >= argc ) { // -(-)log was last argument break; } if( !add_logcat( argv[ i ], LOG_NOTICE ) ) { printlogf( L, "Error", "'%s' is not a valid logging category", argv[ i ] ); exit( -1 ); } } } // registers Lsycnd's core library register_lsyncd( L ); if( check_logcat( "Debug" ) <= settings.log_level ) { // printlogf doesnt support %ld :-( printf( "kernels clocks_per_sec=%ld\n", clocks_per_sec ); } // checks if the user overrode the default runner file if( argp < argc && !strcmp( argv[ argp ], "--runner" ) ) { if (argp + 1 >= argc) { logstring( "Error", "Lsyncd Lua-runner file missing after --runner " ); exit( -1 ); } lsyncd_runner_file = argv[ argp + 1 ]; argp += 2; } if( lsyncd_runner_file ) { // checks if the runner file exists struct stat st; if( stat( lsyncd_runner_file, &st ) ) { printlogf( L, "Error", "Cannot see a runner at '%s'.", lsyncd_runner_file ); exit( -1 ); } // loads the runner file if( luaL_loadfile(L, lsyncd_runner_file ) ) { printlogf( L, "Error", "error loading '%s': %s", lsyncd_runner_file, lua_tostring( L, -1 ) ); exit( -1 ); } } else { // loads the runner from binary if( luaL_loadbuffer( L, runner_out, runner_size, "runner" ) ) { printlogf( L, "Error", "error loading precompiled runner: %s", lua_tostring( L, -1 ) ); exit( -1 ); } } // prepares the runner executing the script { if( lua_pcall( L, 0, LUA_MULTRET, 0 ) ) { printlogf( L, "Error", "preparing runner: %s", lua_tostring( L, -1 ) ); exit( -1 ); } lua_pushlightuserdata( L, (void *) & runner ); // switches the value ( result of preparing ) and the key &runner lua_insert( L, 1 ); // saves the table of the runners functions in the lua registry lua_settable( L, LUA_REGISTRYINDEX ); // saves the error function extras // &callError is the key lua_pushlightuserdata ( L, (void *) &callError ); // &runner[ callError ] the value lua_pushlightuserdata ( L, (void *) &runner ); lua_gettable ( L, LUA_REGISTRYINDEX ); lua_pushstring ( L, "callError" ); lua_gettable ( L, -2 ); lua_remove ( L, -2 ); lua_settable ( L, LUA_REGISTRYINDEX ); } // asserts the Lsyncd's version matches // between runner and core { const char *lversion; lua_getglobal( L, "lsyncd_version" ); lversion = luaL_checkstring( L, -1 ); if( strcmp( lversion, PACKAGE_VERSION ) ) { printlogf( L, "Error", "Version mismatch '%s' is '%s', but core is '%s'", lsyncd_runner_file ? lsyncd_runner_file : "( internal runner )", lversion, PACKAGE_VERSION ); exit( -1 ); } lua_pop( L, 1 ); } // loads the defaults from binary { if( luaL_loadbuffer( L, defaults_out, defaults_size, "defaults" ) ) { printlogf( L, "Error", "loading defaults: %s", lua_tostring( L, -1 ) ); exit( -1 ); } // prepares the defaults if( lua_pcall( L, 0, 0, 0 ) ) { printlogf( L, "Error", "preparing defaults: %s", lua_tostring( L, -1 ) ); exit( -1 ); } } // checks if there is a "-help" or "--help" { int i; for( i = argp; i < argc; i++ ) { if ( !strcmp( argv[ i ], "-help" ) || !strcmp( argv[ i ], "--help" ) ) { load_runner_func( L, "help" ); if( lua_pcall( L, 0, 0, -2 ) ) { exit( -1 ); } lua_pop( L, 1 ); exit( 0 ); } } } // starts the option parser in Lua script { int idx = 1; const char *s; // creates a table with all remaining argv option arguments load_runner_func( L, "configure" ); lua_newtable( L ); while( argp < argc ) { lua_pushnumber ( L, idx++ ); lua_pushstring ( L, argv[ argp++ ] ); lua_settable ( L, -3 ); } // creates a table with the cores event monitor interfaces idx = 0; lua_newtable( L ); while( monitors[ idx ] ) { lua_pushnumber ( L, idx + 1 ); lua_pushstring ( L, monitors[ idx++ ] ); lua_settable ( L, -3 ); } if( lua_pcall( L, 2, 1, -4 ) ) { exit( -1 ); } if( first_time ) { // If not first time, simply retains the config file given s = lua_tostring(L, -1); if( s ) { lsyncd_config_file = s_strdup( s ); } } lua_pop( L, 2 ); } // checks existence of the config file if( lsyncd_config_file ) { struct stat st; // gets the absolute path to the config file // so in case of HUPing the daemon, it finds it again char * apath = get_realpath( lsyncd_config_file ); if( !apath ) { printlogf( L, "Error", "Cannot find config file at '%s'.", lsyncd_config_file ); exit( -1 ); } free( lsyncd_config_file ); lsyncd_config_file = apath; if( stat( lsyncd_config_file, &st ) ) { printlogf( L, "Error", "Cannot find config file at '%s'.", lsyncd_config_file ); exit( -1 ); } // loads and executes the config file if( luaL_loadfile( L, lsyncd_config_file ) ) { printlogf( L, "Error", "error loading %s: %s", lsyncd_config_file, lua_tostring( L, -1 ) ); exit( -1 ); } if( lua_pcall( L, 0, LUA_MULTRET, 0) ) { printlogf( L, "Error", "error preparing %s: %s", lsyncd_config_file, lua_tostring( L, -1 ) ); exit( -1 ); } } #ifdef WITH_INOTIFY open_inotify( L ); #endif #ifdef WITH_FSEVENTS open_fsevents( L ); #endif // adds signal handlers // listens to SIGCHLD, but blocks it until pselect( ) // opens the signal handler up { sigset_t set; sigemptyset( &set ); sigaddset( &set, SIGCHLD ); signal( SIGCHLD, sig_child ); sigprocmask( SIG_BLOCK, &set, NULL ); signal( SIGHUP, sig_handler ); signal( SIGTERM, sig_handler ); signal( SIGINT, sig_handler ); } // runs initializations from runner // it will set the configuration and add watches { load_runner_func( L, "initialize" ); lua_pushboolean( L, first_time ); if( lua_pcall( L, 1, 0, -3 ) ) { exit( -1 ); } lua_pop( L, 1 ); } // // enters the master loop // masterloop( L ); // // cleanup // // tidies up all observances { int i; for( i = 0; i < observances_len; i++ ) { struct observance *obs = observances + i; obs->tidy( obs ); } observances_len = 0; nonobservances_len = 0; } // frees logging categories { int ci; struct logcat *lc; for( ci = 'A'; ci <= 'Z'; ci++ ) { for( lc = logcats[ ci - 'A' ]; lc && lc->name; lc++) { free( lc->name ); lc->name = NULL; } if( logcats[ci - 'A' ] ) { free( logcats[ ci - 'A' ] ); logcats[ ci - 'A' ] = NULL; } } } lua_close( L ); return 0; }
static void testC() { #define getnum(s) ((*s++) - '0') #define getname(s) (nome[0] = *s++, nome) static int32 locks[10]; lua_Object reg[10]; char nome[2]; char *s = luaL_check_string(1); nome[1] = 0; while (1) { switch (*s++) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': lua_pushnumber(*(s - 1) - '0'); break; case 'c': reg[getnum(s)] = lua_createtable(); break; case 'C': { lua_CFunction f = lua_getcfunction(lua_getglobal(getname(s))); lua_pushCclosure(f, getnum(s)); break; } case 'P': reg[getnum(s)] = lua_pop(); break; case 'g': { int32 n=getnum(s); reg[n] = lua_getglobal(getname(s)); break; } case 'G': { int32 n = getnum(s); reg[n] = lua_rawgetglobal(getname(s)); break; } case 'l': locks[getnum(s)] = lua_ref(1); break; case 'L': locks[getnum(s)] = lua_ref(0); break; case 'r': { int32 n = getnum(s); reg[n] = lua_getref(locks[getnum(s)]); break; } case 'u': lua_unref(locks[getnum(s)]); break; case 'p': { int32 n = getnum(s); reg[n] = lua_getparam(getnum(s)); break; } case '=': lua_setglobal(getname(s)); break; case 's': lua_pushstring(getname(s)); break; case 'o': lua_pushobject(reg[getnum(s)]); break; case 'f': lua_call(getname(s)); break; case 'i': reg[getnum(s)] = lua_gettable(); break; case 'I': reg[getnum(s)] = lua_rawgettable(); break; case 't': lua_settable(); break; case 'T': lua_rawsettable(); break; default: luaL_verror("unknown command in `testC': %c", *(s - 1)); } if (*s == 0) return; if (*s++ != ' ') lua_error("missing ` ' between commands in `testC'"); } }
/** * Add the current value of a tile field to the output. * @param L Lua context. * @param value Value of the tile field to add. * @param name Name of the field in Lua code. */ static inline void add_cellint(lua_State *L, int value, const std::string &name) { lua_pushlstring(L, name.c_str(), name.size()); lua_pushinteger(L, value); lua_settable(L, 4); }
static void settabss (lua_State *L, const char *i, const char *v) { lua_pushstring(L, i); lua_pushstring(L, v); lua_settable(L, -3); }
static void storenumber(lua_State *L, const char *name, lua_Number value) { lua_pushstring(L, name); lua_pushnumber(L, value); lua_settable(L, -3); }
static void settabsi (lua_State *L, const char *i, int v) { lua_pushstring(L, i); lua_pushnumber(L, v); lua_settable(L, -3); }
static int vlclua_add_callback( lua_State *L ) { vlclua_callback_t *p_callback; static int i_index = 0; vlc_object_t **pp_obj = luaL_checkudata( L, 1, "vlc_object" ); const char *psz_var = luaL_checkstring( L, 2 ); lua_settop( L, 4 ); /* makes sure that optional data arg is set */ if( !lua_isfunction( L, 3 ) ) return vlclua_error( L ); i_index++; p_callback = (vlclua_callback_t*)malloc( sizeof( vlclua_callback_t ) ); if( !p_callback ) return vlclua_error( L ); /* obj var func data */ lua_getglobal( L, "vlc" ); /* obj var func data vlc */ lua_getfield( L, -1, "callbacks" ); if( lua_isnil( L, -1 ) ) { lua_pop( L, 1 ); lua_newtable( L ); lua_setfield( L, -2, "callbacks" ); lua_getfield( L, -1, "callbacks" ); } /* obj var func data vlc callbacks */ lua_remove( L, -2 ); /* obj var func data callbacks */ lua_pushinteger( L, i_index ); /* obj var func data callbacks index */ lua_insert( L, -4 ); /* obj var index func data callbacks */ lua_insert( L, -4 ); /* obj var callbacks index func data */ lua_createtable( L, 0, 0 ); /* obj var callbacks index func data cbtable */ lua_insert( L, -2 ); /* obj var callbacks index func cbtable data */ lua_setfield( L, -2, "data" ); /* obj var callbacks index func cbtable */ lua_insert( L, -2 ); /* obj var callbacks index cbtable func */ lua_setfield( L, -2, "callback" ); /* obj var callbacks index cbtable */ lua_pushlightuserdata( L, *pp_obj ); /* will be needed in vlclua_del_callback */ /* obj var callbacks index cbtable p_obj */ lua_setfield( L, -2, "private1" ); /* obj var callbacks index cbtable */ lua_pushvalue( L, 2 ); /* will be needed in vlclua_del_callback */ /* obj var callbacks index cbtable var */ lua_setfield( L, -2, "private2" ); /* obj var callbacks index cbtable */ lua_pushlightuserdata( L, p_callback ); /* will be needed in vlclua_del_callback */ /* obj var callbacks index cbtable p_callback */ lua_setfield( L, -2, "private3" ); /* obj var callbacks index cbtable */ lua_settable( L, -3 ); /* obj var callbacks */ lua_pop( L, 3 ); /* <empty stack> */ /* Do not move this before the lua specific code (it somehow changes * the function in the stack to nil) */ p_callback->i_index = i_index; p_callback->i_type = var_Type( *pp_obj, psz_var ); p_callback->L = lua_newthread( L ); /* Do we have to keep a reference to this thread somewhere to prevent garbage collection? */ var_AddCallback( *pp_obj, psz_var, vlclua_callback, p_callback ); return 0; }
static void setnameval (lua_State *L, const char *name, int val) { lua_pushstring(L, name); lua_pushinteger(L, val); lua_settable(L, -3); }
int lua_sr_init_child(void) { sr_lua_load_t *li; int ret; char *txt; memset(&_sr_L_env, 0, sizeof(sr_lua_env_t)); _sr_L_env.L = luaL_newstate(); if(_sr_L_env.L==NULL) { LM_ERR("cannot open lua\n"); return -1; } luaL_openlibs(_sr_L_env.L); lua_sr_openlibs(_sr_L_env.L); /* set SR lib version */ #if LUA_VERSION_NUM >= 502 lua_pushstring(_sr_L_env.L, SRVERSION); lua_setglobal(_sr_L_env.L, "SRVERSION"); #else lua_pushstring(_sr_L_env.L, "SRVERSION"); lua_pushstring(_sr_L_env.L, SRVERSION); lua_settable(_sr_L_env.L, LUA_GLOBALSINDEX); #endif if(_sr_lua_load_list != NULL) { _sr_L_env.LL = luaL_newstate(); if(_sr_L_env.LL==NULL) { LM_ERR("cannot open lua loading state\n"); return -1; } luaL_openlibs(_sr_L_env.LL); lua_sr_openlibs(_sr_L_env.LL); /* set SR lib version */ #if LUA_VERSION_NUM >= 502 lua_pushstring(_sr_L_env.L, SRVERSION); lua_setglobal(_sr_L_env.L, "SRVERSION"); #else lua_pushstring(_sr_L_env.LL, "SRVERSION"); lua_pushstring(_sr_L_env.LL, SRVERSION); lua_settable(_sr_L_env.LL, LUA_GLOBALSINDEX); #endif /* force loading lua lib now */ if(luaL_dostring(_sr_L_env.LL, "sr.probe()")!=0) { txt = (char*)lua_tostring(_sr_L_env.LL, -1); LM_ERR("error initializing Lua: %s\n", (txt)?txt:"unknown"); lua_pop(_sr_L_env.LL, 1); lua_sr_destroy(); return -1; } li = _sr_lua_load_list; while(li) { ret = luaL_dofile(_sr_L_env.LL, (const char*)li->script); if(ret!=0) { LM_ERR("failed to load Lua script: %s (err: %d)\n", li->script, ret); txt = (char*)lua_tostring(_sr_L_env.LL, -1); LM_ERR("error from Lua: %s\n", (txt)?txt:"unknown"); lua_pop(_sr_L_env.LL, 1); lua_sr_destroy(); return -1; } li = li->next; } } LM_DBG("Lua initialized!\n"); return 0; }
static void ListDialog(void) { lua_Object list_tbl = luaL_tablearg(4); lua_Object marks_tbl; int i, ret; char **list; int *marks = NULL; int type = luaL_check_int(1); char* title = luaL_check_string(2); int size = luaL_check_int(3); int opt = luaL_check_int(5); int max_col = luaL_check_int(6); int max_lin = luaL_check_int(7); marks_tbl = lua_getparam(8); if (!lua_isnil(marks_tbl)) { luaL_arg_check(lua_istable(marks_tbl), 8, "table expected"); marks = malloc(sizeof(int) * size); } if (!marks && type==2) lua_error("invalid marks, must not be nil."); list = malloc(sizeof(char *) * size); for (i = 0; i < size; i++) { lua_beginblock(); lua_pushobject(list_tbl); lua_pushnumber(i + 1); list[i] = lua_getstring(lua_gettable()); if (marks) { lua_pushobject(marks_tbl); lua_pushnumber(i + 1); marks[i] = (int) lua_getnumber(lua_gettable()); } lua_endblock(); } ret = IupListDialog(type, title, size, list, opt, max_col, max_lin, marks); if (marks && type==2 && ret!=-1) { for (i = 0; i < size; i++) { lua_beginblock(); lua_pushobject(marks_tbl); lua_pushnumber(i + 1); lua_pushnumber(marks[i]); lua_settable(); lua_endblock(); } } lua_pushnumber(ret); if (marks) free(marks); free(list); }
void ListDirectoryContents(lua_State *L, const char *currentDir) { std::wstring wsConvert; xl::text::transcode::UTF8_to_Unicode(currentDir, strlen(currentDir), wsConvert); const wchar_t *wCurrentDir =wsConvert.c_str(); if (wcscmp(wCurrentDir, L"") == 0) { wchar_t szLogicalDriveStrings[MAX_PATH]; //获取驱动器的内存 wchar_t *szDrive; ::ZeroMemory(szLogicalDriveStrings, MAX_PATH); //将内存清零,第一个参数是申请字符的地址 ::GetLogicalDriveStrings(MAX_PATH-1, szLogicalDriveStrings); //获取磁盘中的所有驱动器 szDrive=(wchar_t*)szLogicalDriveStrings; lua_newtable(L); int index = 1; do { int len = wcslen(szDrive); std::string sDriveConvert; xl::text::transcode::Unicode_to_UTF8(szDrive, wcslen(szDrive), sDriveConvert); const char* volume = sDriveConvert.c_str(); UINT uDriveType = GetDriveType(szDrive); lua_newtable(L); lua_pushnumber(L, 1); lua_pushboolean(L, true); // has children lua_settable(L, -3); lua_pushnumber(L, 2); lua_pushstring(L, volume); lua_settable(L, -3); lua_pushnumber(L, index); lua_insert(L, -2); // 把栈顶的一维索引和rowtable换一下位置, lua_settable(L, -3); // 把刚压栈的一维索引row, 和rowtable弹出, 放在要返回的return table中 index++; szDrive += (len+1); } while(*szDrive!='\x00'); } else { WIN32_FIND_DATA fdFile; HANDLE hFind = NULL; wchar_t wPath[MAX_PATH]; wsprintf(wPath, L"%s\\*", wCurrentDir); if( (hFind = FindFirstFile(wPath, &fdFile)) == INVALID_HANDLE_VALUE) { return; } int index = 1; lua_newtable(L); do { if (wcscmp(fdFile.cFileName, L".") != 0 && wcscmp(fdFile.cFileName, L"..") != 0 && !(fdFile.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && !(fdFile.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)) { lua_newtable(L); lua_pushnumber(L, 1); if (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } lua_settable(L, -3); std::string subDirString; xl::text::transcode::Unicode_to_UTF8(fdFile.cFileName, MAX_PATH, subDirString); lua_pushnumber(L, 2); lua_pushstring(L, subDirString.c_str()); lua_settable(L, -3); lua_pushnumber(L, index);//把一维索引row压栈 lua_insert(L, -2); // 把栈顶的一维索引和rowtable换一下位置, lua_settable(L, -3); // 把刚压栈的一维索引row, 和rowtable弹出, 放在要返回的return table中 index++; } } while(::FindNextFile(hFind, &fdFile)); ::FindClose(hFind); } return; }
/* | Reads the directories entries. | | Params on Lua stack: | 1: absolute path to directory | | Returns on Lua stack: | a table of directory names. | names are keys | values are boolean true on dirs. */ static int l_readdir( lua_State *L ) { const char * dirname = luaL_checkstring( L, 1 ); DIR *d; d = opendir( dirname ); if( d == NULL ) { printlogf( L, "Error", "cannot open dir [%s].", dirname ); return 0; } lua_newtable( L ); while( !hup && !term ) { struct dirent *de = readdir( d ); bool isdir; if( de == NULL ) // finished { break; } // ignores . and .. if( !strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ) ) { continue; } if( de->d_type == DT_UNKNOWN ) { // must call stat on some systems :-/ // ( e.g. ReiserFS ) char *entry = s_malloc( strlen( dirname ) + strlen( de->d_name ) + 2 ); struct stat st; strcpy( entry, dirname ); strcat( entry, "/" ); strcat( entry, de->d_name ); lstat( entry, &st ); isdir = S_ISDIR( st.st_mode ); free( entry ); } else { // otherwise readdir can be trusted isdir = de->d_type == DT_DIR; } // adds this entry to the Lua table lua_pushstring( L, de->d_name ); lua_pushboolean( L, isdir ); lua_settable( L, -3 ); } closedir( d ); return 1; }
static int m_img_get(lua_State * L) { int j; const char *s; image **a = (image **) luaL_checkudata(L, 1, TYPE_IMG); /* k u */ image_dict *d = img_dict(*a); if (d == NULL) { luaL_error(L, "invalid image dictionary"); } s = lua_tostring(L, 2); if (lua_key_eq(s,width)) { if (is_wd_running(*a)) { lua_pushnil(L); } else { lua_pushinteger(L, img_width(*a)); } } else if (lua_key_eq(s,height)) { if (is_ht_running(*a)) { lua_pushnil(L); } else { lua_pushinteger(L, img_height(*a)); } } else if (lua_key_eq(s,depth)) { if (is_dp_running(*a)) { lua_pushnil(L); } else { lua_pushinteger(L, img_depth(*a)); } } else if (lua_key_eq(s,transform)) { lua_pushinteger(L, img_transform(*a)); } else if (lua_key_eq(s,filename)) { if (img_filename(d) == NULL || strlen(img_filename(d)) == 0) { lua_pushnil(L); } else { lua_pushstring(L, img_filename(d)); } } else if (lua_key_eq(s,visiblefilename)) { if (img_visiblefilename(d) == NULL || strlen(img_visiblefilename(d)) == 0) { lua_pushnil(L); } else { lua_pushstring(L, img_visiblefilename(d)); } } else if (lua_key_eq(s,keepopen)) { lua_pushboolean(L, img_keepopen(d)); } else if (lua_key_eq(s,filepath)) { if (img_filepath(d) == NULL || strlen(img_filepath(d)) == 0) { lua_pushnil(L); } else { lua_pushstring(L, img_filepath(d)); } } else if (lua_key_eq(s,attr)) { if (img_attr(d) == NULL || strlen(img_attr(d)) == 0) { lua_pushnil(L); } else { lua_pushstring(L, img_attr(d)); } } else if (lua_key_eq(s,page)) { if (img_pagename(d) != NULL && strlen(img_pagename(d)) != 0) { lua_pushstring(L, img_pagename(d)); } else { lua_pushinteger(L, img_pagenum(d)); } } else if (lua_key_eq(s,pages)) { lua_pushinteger(L, img_totalpages(d)); } else if (lua_key_eq(s,xsize)) { if ((img_rotation(d) & 1) == 0) { lua_pushinteger(L, img_xsize(d)); } else { lua_pushinteger(L, img_ysize(d)); } } else if (lua_key_eq(s,ysize)) { if ((img_rotation(d) & 1) == 0) { lua_pushinteger(L, img_ysize(d)); } else { lua_pushinteger(L, img_xsize(d)); } } else if (lua_key_eq(s,xres)) { lua_pushinteger(L, img_xres(d)); } else if (lua_key_eq(s,yres)) { lua_pushinteger(L, img_yres(d)); } else if (lua_key_eq(s,rotation)) { lua_pushinteger(L, img_rotation(d)); } else if (lua_key_eq(s,colorspace)) { if (img_colorspace(d) == 0) { lua_pushnil(L); } else { lua_pushinteger(L, img_colorspace(d)); } } else if (lua_key_eq(s,colordepth)) { if (img_colordepth(d) == 0) { lua_pushnil(L); } else { lua_pushinteger(L, img_colordepth(d)); } } else if (lua_key_eq(s,imagetype)) { j = img_type(d); if (j >= 0 && j <= img_types_max) { if (j == IMG_TYPE_NONE) { lua_pushnil(L); } else { lua_pushstring(L, img_types[j]); } } else { lua_pushnil(L); } } else if (lua_key_eq(s,pagebox)) { j = img_pagebox(d); if (j < 0 || j >= img_pageboxes_max) { j = 0; } lua_push_img_pagebox(L, j); } else if (lua_key_eq(s,bbox)) { if (!img_is_bbox(d)) { img_bbox(d)[0] = img_xorig(d); img_bbox(d)[1] = img_yorig(d); img_bbox(d)[2] = img_xorig(d) + img_xsize(d); img_bbox(d)[3] = img_yorig(d) + img_ysize(d); } lua_newtable(L); lua_pushinteger(L, 1); lua_pushinteger(L, img_bbox(d)[0]); lua_settable(L, -3); lua_pushinteger(L, 2); lua_pushinteger(L, img_bbox(d)[1]); lua_settable(L, -3); lua_pushinteger(L, 3); lua_pushinteger(L, img_bbox(d)[2]); lua_settable(L, -3); lua_pushinteger(L, 4); lua_pushinteger(L, img_bbox(d)[3]); lua_settable(L, -3); } else if (lua_key_eq(s,objnum)) { if (img_objnum(d) == 0) { lua_pushnil(L); } else { lua_pushinteger(L, img_objnum(d)); } } else if (lua_key_eq(s,index)) { if (img_index(d) == 0) { lua_pushnil(L); } else { lua_pushinteger(L, img_index(d)); } } else if (lua_key_eq(s,stream)) { if (img_type(d) != IMG_TYPE_PDFSTREAM || img_pdfstream_ptr(d) == NULL || img_pdfstream_stream(d) == NULL || strlen(img_pdfstream_stream(d)) == 0) { lua_pushnil(L); } else { lua_pushstring(L, img_pdfstream_stream(d)); } } else if (lua_key_eq(s,ref_count)) { lua_pushinteger(L, img_luaref(d)); } else { lua_pushnil(L); } return 1; }
void PutStrToArray(lua_State *L, int key, const char* str) { lua_pushinteger(L, key); lua_pushstring(L, str); lua_settable(L, -3); }