int main(void) { lua_State *L; L = luaL_newstate(); /* Create Lua state variable */ luaL_openlibs(L); /* Load Lua libraries */ if (luaL_loadfile(L, "callfuncscript.lua")) /* Load but don't run the Lua script */ bail(L, "luaL_loadfile() failed"); /* Error out if file can't be read */ // 这行非常重要 必须先调用 if (lua_pcall(L, 0, 0, 0)) /* PRIMING RUN. FORGET THIS AND YOU'RE TOAST */ bail(L, "lua_pcall() failed"); /* Error out if Lua file has an error */ fprintf(stderr, "before get global----------------"); stackDump(L); // me = { name = "sunzixiang", age = 27} //从Lua里面取得me这个table,并压入栈 lua_getglobal(L, "me"); stackDump(L); if (!lua_istable(L, -1)) { printf("error! me is not a table"); } fprintf(stderr, "after get global----------------"); stackDump(L); //往栈里面压入一个key:name lua_pushstring(L, "name"); fprintf(stderr, "after push string----------------"); stackDump(L); //取得-2位置的table,然后把栈顶元素弹出,取出table[name]的值并压入栈 // lua_gettable 比较特殊 做的一系列操作 // -2 存放着table -1 存放着key // lua_gettable 时 把key弹出 把value放进去 // int lua_gettable (lua_State *L, int index); // Pushes onto the stack the value t[k], where t is the value at the given index and k is the value at the top of the stack. // This function pops the key from the stack, pushing the resulting value in its place. As in Lua, this function may trigger a metamethod for the "index" event (see §2.4). // Returns the type of the pushed value. lua_gettable(L, -2); stackDump(L); //输出栈顶的name fprintf(stderr, "name = %s\n", lua_tostring(L, -1)); fprintf(stderr, "after get table----------------"); stackDump(L); //把栈顶元素弹出去 lua_pop(L, 1); fprintf(stderr, "after pop----------------"); stackDump(L); //压入另一个key:age lua_pushstring(L, "age"); stackDump(L); //取出-2位置的table,把table[age]的值压入栈 lua_gettable(L, -2); stackDump(L); fprintf(stderr, "age = %td", lua_tointeger(L, -1)); return 0; }
int docall (lua_State *L, int narg, int nret) { #if 1 int status; int base = lua_gettop(L) - narg; /* function index */ // printf("<===%d (%d)\n", base, narg); lua_pushcfunction(L, traceback); /* push traceback function */ lua_insert(L, base); /* put it under chunk and args */ status = lua_pcall(L, narg, nret, base); lua_remove(L, base); /* remove traceback function */ /* force a complete garbage collection in case of errors */ if (status != 0) { lua_pop(L, 1); lua_gc(L, LUA_GCCOLLECT, 0); } // printf(">===%d (%d) [%d]\n", lua_gettop(L), nret, status); if (lua_gettop(L) != nret + (base - 1)) { stackDump(L); // assert(0); lua_settop(L, base); } return status; #else int status=0; int base = lua_gettop(L) - narg; /* function index */ lua_call(L, narg, nret); return status; #endif }
int main (void) { lua_State *L = lua_open(); lua_newtable(L); lua_pushstring(L, "key-a"); lua_pushstring(L, "I-am-value-9"); lua_settable(L, -3); t_shallow_copy(L, 1); lua_pushstring(L, "key-a"); lua_pushstring(L, "I-am-value-8888"); lua_settable(L, -3); stackDump(L, "table"); PrintTable(L); lua_pop(L, 1); PrintTable(L); Debug("Imadfdfa[%d] [%s]\n",1231, "dadd"); return 0; }
static void puntCatcher(struct _pf_error *err, int typeId) /* Try and catch the punt. */ { struct _pf_err_catch *catcher; struct _pf_type *errType = _pf_type_table[typeId]; struct _pf_base *errBase = errType->base; for (catcher = errCatchStack; catcher != NULL; catcher = catcher->next) { struct _pf_type *catchType = _pf_type_table[catcher->catchType]; struct _pf_base *catchBase = catchType->base; if (_pf_base_is_ancestor(errBase, catchBase)) break; } if (catcher) { catcher->err = err; unwindStackTo(catcher->act); errCatchStack = catcher; longjmp(catcher->jmpBuf, -1); } else { if (_pf_activation_stack != NULL) { fprintf(stderr, "\n----------start stack dump---------\n"); stackDump(stderr); } reportErrToFile(err, stderr); exit(-1); } }
extern void getLuaTable() { lua_getglobal(lua_state,"testtable"); if (lua_istable(lua_state,-1)) { lua_pushstring(lua_state, "name"); lua_gettable(lua_state, -2); printf("Get the testtable['name'] = %s\n", lua_tostring(lua_state, -1)); stackDump(); // lua堆栈是向下递减的 0开始 top指向永远是0 // 但涉及堆栈使用的函数 都实现了 正数向负数转化的过程 //lua_pop(lua_state, -2); lua_pop(lua_state, 1); //lua_pushinteger(lua_state, 1); lua_pushnumber(lua_state, 1); lua_gettable(lua_state, -2); //lua_getfield(lua_state, -1, "1"); //lua_rawgeti(lua_state, -1, 1); //printf("Get the testtable['name'] = %s\n", lua_tostring(lua_state, -1)); printf("Get the testtable[1] = %f\n", lua_tonumber(lua_state,-1)); } else { printf("testtable is not TABLE type\n"); } }
void LuaController::runScript() { if (m_clearOnExecute->isChecked()) m_scriptLog->clear(); if (luaL_loadstring(m_L,qPrintable(m_scriptEditor->toPlainText())) != 0) { stackDump(); //prints errors... m_runLoop->setChecked(false); } else if (lua_pcall(m_L, 0, 0, 0)!=0) { stackDump(); //prints errors... m_runLoop->setChecked(false); } else lua_settop(m_L,0); // empty stack }
void stackOutput() { vector<const void *> stack; stackDump(&stack); vector<pair<string, string> > tokens; if(FLAGS_addr2line) { string line = "addr2line -f -e " + exeName() + " "; for(int i = 0; i < stack.size(); i++) line += Format("%08x ", (unsigned int)stack[i]); line += "> addr2linetmp.txt"; int rv = system(line.c_str()); if(!rv) { { ifstream ifs("addr2linetmp.txt"); string lin; while(getline(ifs, lin)) { string tlin; getline(ifs, tlin); tokens.push_back(make_pair(lin, tlin)); } } unlink("addr2linetmp.txt"); } else { dprintf("Couldn't call addr2line\n"); return; } { string line = "c++filt -n -s gnu-v3 "; for(int i = 0; i < tokens.size(); i++) line += tokens[i].first + " "; line += "> cppfilttmp.txt"; int rv = system(line.c_str()); if(!rv) { { ifstream ifs("cppfilttmp.txt"); string lin; int ct = 0; while(getline(ifs, lin)) { if(lin.size() && lin[0] == '_') lin.erase(lin.begin()); dprintf(" %s - %s", tokens[ct].second.c_str(), lin.c_str()); ct++; } } unlink("cppfilttmp.txt"); } else { dprintf("Couldn't call c++filt\n"); return; } } } else { for(int i = 0; i < stack.size(); i++) dprintf(" %08x", (unsigned int)stack[i]); } dprintf("\n"); }
void ScriptApiBase::realityCheck() { int top = lua_gettop(m_luastack); if(top >= 30){ dstream<<"Stack is over 30:"<<std::endl; stackDump(dstream); scriptError("Stack is over 30 (reality check)"); } }
void ScriptApiBase::realityCheck() { int top = lua_gettop(m_luastack); if (top >= 30) { dstream << "Stack is over 30:" << std::endl; stackDump(dstream); std::string traceback = script_get_backtrace(m_luastack); throw LuaError("Stack is over 30 (reality check)\n" + traceback); } }
/// Notifies observers int luaEvent::notify(lua_State *L ) { #ifdef DEBUG_OBSERVER printf("\nevent::notifyObservers\n"); luaStackToQString(12); stackDump(luaL); #endif double time = luaL_checknumber(luaL, -1); EventSubjectInterf::notify(time); return 0; }
int main(void) { lua_State *L = luaL_newstate(); lua_pushboolean(L, 1); lua_pushnumber(L, 10); lua_pushnil(L); lua_pushstring(L, "hello"); stackDump(L); lua_pushvalue(L, -4); stackDump(L); lua_replace(L, 3); stackDump(L); lua_settop(L, 6); stackDump(L); lua_remove(L, -3); stackDump(L); lua_settop(L, -5); stackDump(L); lua_close(L); return 0; }
void Hard_Fault_Handler(uint32_t stack[]) { /* Go to infinite loop when Hard Fault exception occurs */ //__get_MSP(); // printErrorMsg("in fault"); //ITM_SendChar('0'); //stackDump(stack[]); stackDump(stack); __ASM volatile("BKPT #01"); while (1) { } }
void test2() { lua_State *L = luaL_newstate(); lua_pushboolean(L, 0); lua_pushnumber(L, 10); lua_pushnil(L); lua_pushstring(L, "hello"); lua_pushvalue(L, -5); //lua_pop(L, 3); //API用索引来访问栈中的元素。在栈中的第一个元素(也就是第一个被压入栈的)有索引1,下一个有索引2,以此类推。我们也可以用栈顶作为参照来存取元素,利用负索引。在这种情况下,-1指出栈顶元素(也就是最后被压入的),-2指出它的前一个元素,以此类推。 stackDump(L); }
QStringList functionList(lua_State* luaState) { if (luaL_dostring(luaState,functionScript) != 0) { stackDump(luaState); //prints errors... return QStringList(); } // search for main function in lua script file lua_getglobal(luaState, "main"); if (lua_pcall(luaState, 0, 1, 0) != 0) { qWarning("LUA Error %s\n!",lua_tostring(luaState, -1)); lua_pop(luaState,1); return QStringList(); } if (!lua_isstring(luaState, -1)) { lua_settop(luaState,0); // empty stack return QStringList(); } QStringList retVal = QString(lua_tostring(luaState, -1)).split(',', QString::SkipEmptyParts); // Add library names additionally for (int i=0; i<retVal.size(); ++i) { QString f(retVal.at(i)); int index = f.indexOf('.'); while (index != -1) { QString lib(f.left(index)); if (!retVal.contains(lib)) retVal.append(lib); index = f.indexOf('.', index+1); } } // sort list alphabetically retVal.sort(); lua_settop(luaState,0); // empty stack return retVal; }
errors stackPush(stack *stk, stackData const value) { if(!stackOk(stk)) {ASSERT_OK(stk);}; stk->data[stk->posEndElem] = value; stk->posEndElem++; if(stk->posEndElem == stk->maxLength) { stackData* checkRealloc = NULL; checkRealloc = (stackData*) realloc(stk->data, stk->maxLength * 2 * sizeof(*(stk->data))); if(checkRealloc != NULL) { stk->maxLength *= 2; stk->data = checkRealloc; }else { STACK_ERRNO = STACKFULL; stackDump(stk); } } if(!stackOk(stk)) {ASSERT_OK(stk);}; return OK; }
stackData stackPop(stack *stk) { if(!stackOk(stk)) {ASSERT_OK(stk);}; if(stk->posEndElem == 0) { STACK_ERRNO = STACKNULLSIZE; stackDump(stk); return STACKNULLSIZE; } stk->posEndElem--; if((2 * stk->posEndElem < stk->maxLength)&&(stk->maxLength > INITIAL_STACK_SIZE)) { stk->maxLength /= 2; stk->data = (stackData*) realloc(stk->data, stk->maxLength * sizeof (*(stk->data))); } if(!stackOk(stk)) {ASSERT_OK(stk);}; return stk->data[stk->posEndElem]; }
int main(void) { lua_State* L = luaL_newstate(); lua_pushnumber(L, 3.5); stackDump(L); /* 3.5 */ lua_pushstring(L, "hello"); stackDump(L); /* 3.5 'hello' */ lua_pushnil(L); stackDump(L); /* 3.5 'hello' nil */ lua_pushvalue(L, -2); stackDump(L); /* 3.5 'hello' nil 'hello' */ lua_remove(L, 1); stackDump(L); /* 'hello' nil 'hello' */ lua_insert(L, -2); stackDump(L); /* 'hello' 'hello' nil */ return 0; }
// 24.2.3���Դ�ӡ��ջ void stackTest(lua_State *L) { lua_pushboolean(L, 1); lua_pushnumber(L, 10); lua_pushnil(L); lua_pushstring(L, "hello"); stackDump(L); lua_pushvalue(L, -4); stackDump(L); lua_replace(L, 3); stackDump(L); lua_settop(L, 6); stackDump(L); lua_remove(L, -3); stackDump(L); lua_settop(L, -5); stackDump(L); }
void pf_stackDump() /* Handle user-requested stack dump. */ { fprintf(stdout, "----------application requested stack dump---------\n"); stackDump(stdout); }
/** should return an error code **/ bool CLuaVM::handleError(lua_State* state,std::string& errorDescription){ lua_Debug d; fus::TCharStringBuilder stream(""); // 2nd parameter is the level of function 0 => current function // n+1 level calls level nfunction // recupere le message de debug implante par lua luabind::object obj(luabind::from_stack(state, -1) ); if(lua_getstack(state, 1, &d) != 1 ){ errorDescription = "Could not retrieve item from stack at level [1]. Dump stack... "; //int top = lua_gettop(L); stackDump(state); return false; } // could dumpa stack //Returns information about a specific function or function invocation // must be called with a valid lua_Debug, // 's','l','n' fills certain fields of lua_Debug // l => line // Returns 0 on error //object error_stream(from_stack(e.state(), -1)); // regarder ici comment on pop le message pr en pusher un plus complet // http://www.rasterbar.com/products/luabind/docs.html#error-handling if(lua_getinfo(state, "Sln", &d) == 0){ //stream(); errorDescription = "Couldn't retrieve info from stack"; return false; } //a "printable" version of source d.short_src std::string src(d.source); // if true, then we have the filename // otherwise it is the string defining function if( !src.empty() && src[0] == '@'){ // //src = stream("Line [")( d.currentline ); stream("] of file ");//("\" in code:\n"); } else { stream("In code \n"); } stream(d.short_src) ("\nDescription of the problem:\t")("\n"); stream(obj); //(lua_tostring(mLuaState, -1)) // name is a reasonable name for a function // namewhat a more descriptible if (d.name != 0){ try { stream("(")( d.namewhat )( " " )(d.name)(")"); } catch(std::exception& e){ _LOG_ERROR << "Lua error"; } } else { stream("d.name == 0"); } //int luaL_LOG_ERROR (lua_State *L, const char *fmt, ...); //lua_pushstring(mLuaState, stream.str().c_str()); //_errorMessage = stream.str();//lua_tostring(mLuaState,-1); errorDescription = stream.str() ; return true; }
static void thread_resume_instance(instance_t i) { _DEBUG("Resuming instance: %p %d lua_State (%p)\n",i,i->flags,i->L); lua_State * L=i->L; switch(i->flags) { case I_CREATED: lstage_initinstance(i); break; case I_WAITING_IO: i->flags=I_READY; lua_pushliteral(L,STAGE_HANDLER_KEY); lua_gettable(L,LUA_REGISTRYINDEX); lua_pushboolean(L,1); stackDump(L,"teste"); if(lua_pcall(i->L,1,0,0)) { const char * err=lua_tostring(L,-1); fprintf(stderr,"[I_WAITING_IO] Error resuming instance: %s\n",err); } break; case I_TIMEOUT_IO: i->flags=I_READY; lua_pushliteral(L,STAGE_HANDLER_KEY); lua_gettable(L,LUA_REGISTRYINDEX); lua_pushboolean(L,0); if(lua_pcall(i->L,1,0,0)) { const char * err=lua_tostring(L,-1); fprintf(stderr,"[I_TIMEOUT_IO] Error resuming instance: %s\n",err); } break; // Ready to execute event case I_READY: if(i->ev) { lua_pushliteral(L,STAGE_HANDLER_KEY); lua_gettable(L,LUA_REGISTRYINDEX); lua_pushcfunction(L,mar_decode); lua_pushlstring(L,i->ev->data,i->ev->len); lstage_destroyevent(i->ev); i->ev=NULL; if(lua_pcall(L,1,1,0)) { const char * err=lua_tostring(L,-1); fprintf(stderr,"[I_READY] Error decoding event: %s\n",err); break; } int n= #if LUA_VERSION_NUM < 502 luaL_getn(L,2); #else luaL_len(L,2); #endif int j; for(j=1;j<=n;j++) lua_rawgeti(L,2,j); lua_remove(L,2); i->args=n; // Increment processed count - used to build statistics LOCK(i->stage); int processedCount = i->stage->processed; i->stage->processed = processedCount + 1; UNLOCK(i->stage); } else { lua_pushliteral(L,STAGE_HANDLER_KEY); lua_gettable(L,LUA_REGISTRYINDEX); i->args=0; } if(lua_pcall(L,i->args,0,0)) { const char * err=lua_tostring(L,-1); fprintf(stderr,"[I_READY] Error resuming instance: %s\n",err); } break; case I_WAITING_EVENT: return; case I_WAITING_CHANNEL: return; case I_IDLE: break; } _DEBUG("Instance Yielded: %p %d lua_State (%p)\n",i,i->flags,i->L); if(i->flags==I_WAITING_CHANNEL) { //lua_settop(i->L,0); lstage_lfqueue_try_push(i->channel->wait_queue,&i); return; } else if(i->flags==I_READY || i->flags==I_IDLE) { lstage_putinstance(i); } }
/// Creates an observer int luaEvent::createObserver( lua_State *L ) { #ifdef DEBUG_OBSERVER stackDump(luaL); #endif // recupero a referencia da celula lua_rawgeti(luaL, LUA_REGISTRYINDEX, ref); // flags para a definição do uso de compressão // na transmissão de datagramas e da visibilidade // dos observadores Udp Sender bool compressDatagram = false, obsVisible = true; int top = lua_gettop(luaL); int typeObserver = (int)luaL_checkinteger(luaL, 1); QStringList allAttribs, cols; allAttribs.push_back("EventTime"); allAttribs.push_back("Periodicity"); allAttribs.push_back("Priority"); // Recupera a tabela de parametros //if(! lua_istable(luaL, top - 1) ) //{ // if (! QUIET_MODE ) // qWarning("Warning: Parameter table not found."); //} //else //{ lua_pushnil(luaL); while(lua_next(luaL, top - 1) != 0) { QString key; if (lua_type(luaL, -2) == LUA_TSTRING) key = QString( luaL_checkstring(luaL, -2)); switch (lua_type(luaL, -1)) { case LUA_TSTRING: { QString value( luaL_checkstring(luaL, -1)); cols.push_back(value); break; } case LUA_TBOOLEAN: { bool val = lua_toboolean(luaL, -1); if (key == "visible") obsVisible = val; else // if (key == "compress") compressDatagram = val; } default: break; } lua_pop(luaL, 1); } // } if (cols.isEmpty()) { if (! QUIET_MODE ) qWarning("Warning: The Parameters Table is empty."); cols << "" << ""; } ObserverTextScreen *obsText = 0; ObserverTable *obsTable = 0; ObserverLogFile *obsLog = 0; ObserverUDPSender *obsUDPSender = 0; int obsId = -1; switch (typeObserver) { case TObsTextScreen: obsText = (ObserverTextScreen*) EventSubjectInterf::createObserver(TObsTextScreen); if (obsText) { obsId = obsText->getId(); } else { if (! QUIET_MODE) qWarning("%s", TerraMEObserver::MEMORY_ALLOC_FAILED); } break; case TObsLogFile: obsLog = (ObserverLogFile*) EventSubjectInterf::createObserver(TObsLogFile); if (obsLog) { obsId = obsLog->getId(); } else { if (! QUIET_MODE) qWarning("%s", TerraMEObserver::MEMORY_ALLOC_FAILED); } break; case TObsTable: obsTable = (ObserverTable *) EventSubjectInterf::createObserver(TObsTable); if (obsTable) { obsId = obsTable->getId(); } else { if (! QUIET_MODE) qWarning("%s", TerraMEObserver::MEMORY_ALLOC_FAILED); } break; case TObsUDPSender: obsUDPSender = (ObserverUDPSender *) EventSubjectInterf::createObserver(TObsUDPSender); if (obsUDPSender) { obsId = obsUDPSender->getId(); obsUDPSender->setCompressDatagram(compressDatagram); if (obsVisible) obsUDPSender->show(); } else { if (! QUIET_MODE) qWarning("%s", TerraMEObserver::MEMORY_ALLOC_FAILED); } break; default: if (! QUIET_MODE ) { qWarning("Error: In this context, the code '%s' does not " "correspond to a valid type of Observer.", getObserverName(typeObserver) ); } return 0; } QStringList obsAttribs; obsAttribs = allAttribs; observedAttribs = allAttribs; /// Define alguns parametros do observador instanciado --------------------------------------------------- if (obsLog) { obsLog->setHeaders(obsAttribs); if (cols.at(0).isNull() || cols.at(0).isEmpty()) { if (! QUIET_MODE ) { qWarning("Warning: Filename was not specified, using a " "default \"%s\".", qPrintable(DEFAULT_NAME)); } obsLog->setFileName(DEFAULT_NAME + ".csv"); } else { obsLog->setFileName(cols.at(0)); } // caso não seja definido, utiliza o default ";" if ((cols.size() < 2) || cols.at(1).isNull() || cols.at(1).isEmpty()) { if (! QUIET_MODE ) qWarning("Warning: Separator not defined, using \";\"."); obsLog->setSeparator(); } else { obsLog->setSeparator(cols.at(1)); } lua_pushnumber(luaL, obsId); return 1; } if (obsText) { obsText->setHeaders(obsAttribs); lua_pushnumber(luaL, obsId); return 1; } if (obsTable) { if ((cols.size() < 1) || (cols.size() < 2) || cols.at(0).isNull() || cols.at(0).isEmpty() || cols.at(1).isNull() || cols.at(1).isEmpty()) { if (! QUIET_MODE ) qWarning("Warning: Column title not defined."); } obsTable->setColumnHeaders(cols); obsTable->setLinesHeader(obsAttribs); lua_pushnumber(luaL, obsId); return 1; } if (obsUDPSender) { obsUDPSender->setAttributes(obsAttribs); if (cols.isEmpty()) { if (! QUIET_MODE ) qWarning("Warning: Port not defined."); } else { obsUDPSender->setPort(cols.at(0).toInt()); } // broadcast if ((cols.size() == 1) || ((cols.size() == 2) && cols.at(1).isEmpty()) ) { if (! QUIET_MODE ) qWarning("Warning: Observer will send to broadcast."); obsUDPSender->addHost(BROADCAST_HOST); } else { // multicast or unicast for(int i = 1; i < cols.size(); i++){ if (! cols.at(i).isEmpty()) obsUDPSender->addHost(cols.at(i)); } } lua_pushnumber(luaL, obsId); return 1; } return 0; }