You can subscribe to this list here.
2005 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(191) |
Jul
(1) |
Aug
(2) |
Sep
|
Oct
|
Nov
(238) |
Dec
(68) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2006 |
Jan
(104) |
Feb
(518) |
Mar
(302) |
Apr
(211) |
May
(311) |
Jun
(55) |
Jul
(6) |
Aug
(35) |
Sep
(76) |
Oct
(50) |
Nov
(37) |
Dec
(340) |
2007 |
Jan
(23) |
Feb
(107) |
Mar
(98) |
Apr
(60) |
May
(136) |
Jun
(371) |
Jul
(175) |
Aug
(74) |
Sep
(3) |
Oct
(2) |
Nov
(53) |
Dec
(129) |
2008 |
Jan
(337) |
Feb
(23) |
Mar
(18) |
Apr
(4) |
May
(3) |
Jun
|
Jul
|
Aug
(4) |
Sep
|
Oct
(33) |
Nov
|
Dec
(26) |
2009 |
Jan
(4) |
Feb
(1) |
Mar
(15) |
Apr
|
May
(35) |
Jun
(11) |
Jul
|
Aug
|
Sep
(19) |
Oct
(26) |
Nov
(11) |
Dec
(11) |
2010 |
Jan
(4) |
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
(8) |
Sep
|
Oct
|
Nov
(8) |
Dec
(7) |
2011 |
Jan
|
Feb
|
Mar
(4) |
Apr
(8) |
May
(5) |
Jun
(8) |
Jul
(1) |
Aug
|
Sep
|
Oct
(5) |
Nov
(13) |
Dec
|
From: John L. <jr...@us...> - 2005-06-06 23:18:58
|
Update of /cvsroot/wxlua/wxLua/bin In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21720/wxLua/bin Removed Files: README.txt Log Message: remove readme and readd to remove exe --- README.txt DELETED --- |
Update of /cvsroot/wxlua/wxLua/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19476/wxLua/src Removed Files: debug.cpp debugio.cpp dserver.cpp dtarget.cpp internal.cpp interp.cpp library.cpp socket.cpp splttree.cpp staktree.cpp Log Message: moving files to modules dir --- interp.cpp DELETED --- --- internal.cpp DELETED --- --- debugio.cpp DELETED --- --- staktree.cpp DELETED --- --- library.cpp DELETED --- --- socket.cpp DELETED --- --- dserver.cpp DELETED --- --- splttree.cpp DELETED --- --- debug.cpp DELETED --- --- dtarget.cpp DELETED --- |
From: John L. <jr...@us...> - 2005-06-06 23:14:10
|
Update of /cvsroot/wxlua/wxLua/include/wxlua In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19476/wxLua/include/wxlua Removed Files: callback.h debug.h debugio.h defs.h dserver.h dtarget.h internal.h interp.h library.h socket.h splttree.h staktree.h wxlua.h Log Message: moving files to modules dir --- dtarget.h DELETED --- --- debug.h DELETED --- --- defs.h DELETED --- --- staktree.h DELETED --- --- debugio.h DELETED --- --- callback.h DELETED --- --- interp.h DELETED --- --- splttree.h DELETED --- --- dserver.h DELETED --- --- wxlua.h DELETED --- --- socket.h DELETED --- --- library.h DELETED --- --- internal.h DELETED --- |
From: John L. <jr...@us...> - 2005-06-06 23:06:58
|
Update of /cvsroot/wxlua/wxLua/docs In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/docs Modified Files: newdirs.txt Log Message: moved files to the modules directory structure Index: newdirs.txt =================================================================== RCS file: /cvsroot/wxlua/wxLua/docs/newdirs.txt,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** newdirs.txt 1 Jun 2005 18:56:59 -0000 1.1 --- newdirs.txt 6 Jun 2005 23:06:08 -0000 1.2 *************** *** 20,27 **** wxLua/ ! art/ - all images go here, preferably in XPM format ! bin/ - output binaries go here, lua for example build/ - cmake, bakefile stuff here ! docs/ - any generic docs go here include/wxlua/ - headers from "Library" lib/ - output libs go here, wxlualib for example --- 20,27 ---- wxLua/ ! art/ - all images are here, preferably in XPM format ! bin/ - output binaries are built here, lua for example build/ - cmake, bakefile stuff here ! docs/ - generic docs are here include/wxlua/ - headers from "Library" lib/ - output libs go here, wxlualib for example *************** *** 35,43 **** utils/ - generic utils, bin2c for example ------------------------------------------------------------------------------- ! Files: ------------------------------------------------------------------------------- ! wxLua/include/wxlua/* wxlua.h wxLua.h --- 35,95 ---- utils/ - generic utils, bin2c for example + + + wxLua/ + /art/ - images are here, preferably in XPM format + /apps/ - c/c++ application code is here + /build/ - build for all applications + /wxlua/ - wxLua the main IDE for wxLua, the "Standalone" program + /embedded/ - an embedded sample + /runtime/ - a stripped down runtime for wxLua + /bin/ - output binaries are built here, lua for example + /build/ - cmake, bakefile stuff here, may call sub build dirs + /docs/ - any generic docs go here + /lib/ - output libs are built here, wxlualib for example + /samples/ - sample wxlua programs + /name/ - any multifile sample gets its own dir + /utils/ - generic utils, bin2c for example + + /bindings/ - input *.i files to make the "wrappers" + wxluawrap.lua - the main wrapper file + /wxwidgets/ - wrapper files for wxWidgets + /bit/ - the bitwise lib for lua, maybe nothing needed here + /other .i files for other stuff.../ + /wrappers/ - output of the wrapper files may be built here + /wxwidgets/ - output of bindings and wxLuaPrinting, wxLuaHtmlWin + /bit/ - the wrapper is the "src" of the bit library + /output of other .i files for other stuff.../ + + /modules/ - c/c++ code for wxlua + /build/ - to have build files for all of this + /lua/ - lua itself + /include/ + /src/ + /the rest of lua.../ + /wxlua/ - the wxlua library itself + /include/ - internal.h, interp.h, library.h, callback.h + /src/ - internal.cpp, interp.cpp, library.cpp + /wxluasocket/ - lua to cpp sockets (the current lua sockets) + /include/ - debugio.h, dserver.h, socket.h + /src/ - debugio.cpp, dserver.cpp, socket.cpp + /wxluadebug/ - mechanism for getting/showing info from lua + /include/ - debug.h, stacktree, splittree + /src/ - debug.cpp, stacktree, splittree + /wxxmlrpc/ - is is a generic lib right? so don"t prepend wxlua to it? + /include/ - ... Rays stuff + /src/ - ... Rays stuff + /debuggernub/ - this is a generic lib for xmlrpc? don"t prepend wxlua to it + /include/ - ... Rays stuff + /src/ - ... Rays stuff + /wxluadebugger/ - this depends on wxlua so prepend wxlua to it + /include/ - ... Rays stuff + /src/ - ... Rays stuff + ------------------------------------------------------------------------------- ! File name mapping from the original wxLua ------------------------------------------------------------------------------- ! These header files were in wxLua/Library wxlua.h wxLua.h *************** *** 56,60 **** staktree.h wxLuaStackTree.h ! wxLua/src/* debug.cpp wxLuaDebug.cpp --- 108,112 ---- staktree.h wxLuaStackTree.h ! These source files were in wxLua/Library debug.cpp wxLuaDebug.cpp *************** *** 71,74 **** staktree.cpp wxLuaStackTree.cpp ! dtarget.h wxLuaDebugTarget.h moved into include/wxlua from Standalone ! dtarget.cpp wxLuaDebugTarget.cpp move into src from Standalone --- 123,126 ---- staktree.cpp wxLuaStackTree.cpp ! dtarget.h wxLuaDebugTarget.h moved from wxLua/Standalone ! dtarget.cpp wxLuaDebugTarget.cpp moved from wxLua/Standalone |
From: John L. <jr...@us...> - 2005-06-06 23:06:33
|
Update of /cvsroot/wxlua/wxLua/modules/wxlua/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/wxlua/src Added Files: internal.cpp interp.cpp library.cpp Log Message: moved files to the modules directory structure --- NEW FILE: interp.cpp --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaInterpreter // Purpose: A simple class for a C++ wxWidgets program to embed wxLua // Author: John Labenski // Modified by: // Created: 11/05/2002 // RCS-ID: // Copyright: (c) John Labenki // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// // references // http://www.andreas-rozek.de/Lua/index_en.html interesing libraries perhaps #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "interp.h" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif // WX_PRECOMP #include "wxlua/interp.h" #include "wxlua/internal.h" extern int s_wxLuaInterpreter; wxHashMapLuaInterpreter s_wxHashMapLuaInterpreter; // add lua_States created from lua's coroutines #define WXLUA_THREAD_INTERCEPTION extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" #ifdef WXLUA_THREAD_INTERCEPTION // See lua/src/lstate.c for added hook into luaE_newthread() #include "luathread.h" #endif //WXLUA_THREAD_INTERCEPTION } #ifdef WXLUA_THREAD_INTERCEPTION // Hook into function calls to luaE_newthread (calls from coroutine.create/wrap) // and add the new lua_State as a child sharing it's wxLuaStateVariables void wxLuaInterpreter_newthread_handler(lua_State *L, lua_State *L1) { // L is the original lua_State, L1 new child thread wxLuaInterpreter *L_interp = wxFindLuaInterpreter(L); //printf("Adding new lua_State from a thread L=%ld L1=%ld\n", (long)L, (long)L1); fflush(stdout); if (L_interp != NULL) s_wxHashMapLuaInterpreter[L1] = L_interp; } // Hook into function calls to luaE_freethread (calls from coroutine.create/wrap) // and remove the child lua_State void wxLuaInterpreter_freethread_handler(lua_State *WXUNUSED(L), lua_State *L1) { // L is the original lua_State, L1 child thread, don't remove L //printf("Freeing lua_State from a thread L=%ld L1=%ld\n", (long)L, (long)L1); fflush(stdout); s_wxHashMapLuaInterpreter.erase(L1); } static void setupthreadhandlers() { if (luaX_getnewthreadhandler() == NULL) luaX_setnewthreadhandler( wxLuaInterpreter_newthread_handler ); if (luaX_getfreethreadhandler() == NULL) luaX_setfreethreadhandler( wxLuaInterpreter_freethread_handler ); } #endif //WXLUA_THREAD_INTERCEPTION // ---------------------------------------------------------------------------- // Extra wxLua helpers that use the lua_State to find owner wxLuaInterpreter // ---------------------------------------------------------------------------- wxLuaInterpreter *wxFindLuaInterpreter(lua_State *L) { int top = lua_gettop( L ); // try to get the state lua_pushstring( L, "__wxLuaInterpreter" ); lua_gettable( L, LUA_REGISTRYINDEX ); // if nothing was returned or it wasn't a ptr, abort if ( top == lua_gettop(L) || !lua_islightuserdata(L, -1) ) { lua_settop( L, top ); return NULL; } // get the pointer, clean the stack, return wxLuaInterpreter* lI = (wxLuaInterpreter*)lua_touserdata( L, -1 ); lua_settop( L, top ); return lI; } wxLuaStateVariables *wxFindLuaStateVariables(lua_State *L) { wxLuaInterpreter *luaInterpreter = wxFindLuaInterpreter(L); if (luaInterpreter && luaInterpreter->Ok()) return luaInterpreter->GetStateVariables(); return NULL; } // ---------------------------------------------------------------------------- // wxFindWindowByPointer - find a window by it's pointer // return FALSE if doesn't exist, see wxFindWindowByID and wxFindWindowByLabel // ---------------------------------------------------------------------------- static wxWindow *wxFindWindowPointerRecursively(const wxWindow *parent, const wxWindow *win) { wxCHECK_MSG(win, NULL, wxT("invalid window in wxFindWindowPointerRecursively")); if ( parent ) { // see if this is the one we're looking for if ( parent == win ) return (wxWindow*)win; // It wasn't, so check all its children for ( wxWindowList::Node * node = parent->GetChildren().GetFirst(); node; node = node->GetNext() ) { // recursively check each child wxWindow *child_win = (wxWindow *)node->GetData(); wxWindow *retwin = wxFindWindowPointerRecursively(child_win, win); if (retwin) return retwin; } } // Not found return NULL; } // Check to see if wxWidgets still thinks "win" is a valid window // parent is the window to start with, if parent=NULL check all windows static wxWindow* wxFindWindowByPointer(const wxWindow *parent, const wxWindow *win) { wxCHECK_MSG(win, NULL, wxT("Invalid window in wxFindWindowByPointer")); if ( parent ) { // just check parent and all its children return wxFindWindowPointerRecursively(parent, win); } // start at very top of wx's windows for ( wxWindowList::Node * top_node = wxTopLevelWindows.GetFirst(); top_node; top_node = top_node->GetNext() ) { // recursively check each window & its children wxWindow *top_win = top_node->GetData(); wxWindow *retwin = wxFindWindowPointerRecursively(top_win, win); if (retwin) return retwin; } return FALSE; } // ---------------------------------------------------------------------------- // wxLuaCleanupWindows - given a wxList of wxWindows it runs wxFindWindowByPointer // on it to remove dead pointers from the list if only_check=TRUE or // Destroy() the windows and remove them from the list if !only_check. // This is for use with wxLuaStateVariables::m_pWindowList. // returns TRUE if any windows removed, ie. the list has changed // ---------------------------------------------------------------------------- bool wxLuaCleanupWindows(wxList *list, bool only_check) { bool removed = FALSE; wxNode *node = list->GetFirst(); while (node != NULL) { wxWindow *win = (wxWindow *)node->GetData(); if (!win) { wxNode *lastNode = node; node = node->GetNext(); list->DeleteNode(lastNode); } else if (wxFindWindowByPointer(NULL, win) == NULL) { removed = TRUE; wxNode *lastNode = node; node = node->GetNext(); //printf("%d %d\n", int(lastNode), int(node)); fflush(stdout); list->DeleteNode(lastNode); } else if (!only_check) { removed = TRUE; if (win->HasCapture()) win->ReleaseMouse(); // release capture for children since we may be abruptly ending for ( wxWindowList::compatibility_iterator childNode = win->GetChildren().GetFirst(); childNode; childNode = childNode->GetNext() ) { wxWindow *child = childNode->GetData(); list->DeleteObject(child); if (child->HasCapture()) child->ReleaseMouse(); } if (!win->IsBeingDeleted()) { delete win; } // wxLuaWindowDestroyHandler should destroy this node // and also delete all the children and their nodes // it's probably best to start from the top again list->DeleteObject(win); wxPrintf(wxT("%d %d\n"), int(1), int(win)); fflush(stdout); node = list->GetFirst(); } else node = node->GetNext(); } return removed; } // ---------------------------------------------------------------------------- // lua hooks and function replacements for embedding into wxWidgets // ---------------------------------------------------------------------------- int LuaPrint( lua_State *L ) { wxString msg; int i, n = lua_gettop(L); // figure out the types here in c++ land lua_getglobal(L, "tostring"); for (i = 1; i <= n; i++) { if (i > 1) msg.Append(wxT(", ")); if (lua_isstring(L, i)) msg += lua2wx(lua_tostring(L, i)); else if (lua_isnumber(L, i)) msg += wxString::Format(wxT("%lf"), lua_tonumber(L, i)); else if (lua_iscfunction(L, i)) msg += wxString::Format(wxT("C function %ld"), (long int)lua_tocfunction(L, i)); else if (lua_isuserdata(L, i)) msg += wxString::Format(wxT("User data %ld"), (long int)lua_touserdata(L, i)); else if (lua_isboolean(L, i)) msg += lua_toboolean(L,i) ? wxT("true") : wxT("false"); else if (lua_isnil(L,i)) msg += wxT("nil"); else if (lua_isnone(L,i)) msg += wxT("unknown"); else msg += wxString::Format(wxT("%s:%p"), lua_typename(L,lua_type(L,i)), lua_topointer(L,i)); } if (!msg.IsEmpty()) { wxLuaInterpreter *luaInterpreter = wxFindLuaInterpreter(L); if (luaInterpreter) { wxLuaEvent event(wxEVT_LUA_CONSOLE, luaInterpreter->GetId(), luaInterpreter); event.SetString(msg); luaInterpreter->SendEvent( event ); } } return 0; // no items put onto stack } // copied from the Lua 5.0.1 debug library #define LEVELS1 12 /* size of the first part of the stack */ #define LEVELS2 10 /* size of the second part of the stack */ // copied from the Lua 5.0.1 debug library int LuaTraceback(lua_State *L) { int level = 1; // skip level 0 (it's this function) int firstpart = 1; // still before eventual `...' lua_Debug ar; if (lua_gettop(L) == 0) lua_pushliteral(L, ""); else if (!lua_isstring(L, 1)) // no string message return 1; else lua_pushliteral(L, "\n"); lua_pushliteral(L, "stack traceback:"); while (lua_getstack(L, level++, &ar)) { if (level > LEVELS1 && firstpart) { // no more than `LEVELS2' more levels? if (!lua_getstack(L, level+LEVELS2, &ar)) level--; // keep going else { lua_pushliteral(L, "\n\t..."); // too many levels while (lua_getstack(L, level+LEVELS2, &ar)) // find last levels level++; } firstpart = 0; continue; } lua_pushliteral(L, "\n\t"); lua_getinfo(L, "Snl", &ar); lua_pushfstring(L, "%s:", ar.short_src); if (ar.currentline > 0) lua_pushfstring(L, "%d:", ar.currentline); switch (*ar.namewhat) { case 'g': // global case 'l': // local case 'f': // field case 'm': // method lua_pushfstring(L, " in function `%s'", ar.name); break; default: { if (*ar.what == 'm') // main? lua_pushfstring(L, " in main chunk"); else if (*ar.what == 'C' || *ar.what == 't') lua_pushliteral(L, " ?"); // C function or tail call else lua_pushfstring(L, " in function <%s:%d>", ar.short_src, ar.linedefined); } } lua_concat(L, lua_gettop(L)); } lua_concat(L, lua_gettop(L)); return 1; } int LuaAlert( lua_State *L ) { wxLuaInterpreter *luaInterpreter = wxFindLuaInterpreter(L); if (luaInterpreter) { wxString msg = lua2wx(lua_tostring(L, 1)); wxLuaEvent event(wxEVT_LUA_ERROR, luaInterpreter->GetId(), luaInterpreter); event.SetString(msg); long line = -1; wxString lineStr = msg; // Why can't I fill a lua_Debug here? Try to get the line number // by parsing the error message that looks like this, 1 is linenumber // [string "a = 1("]:1: unexpected symbol near `<eof>' while(!lineStr.IsEmpty()) { lineStr = lineStr.AfterFirst(wxT(']')); if ((lineStr.Length() > 0) && (lineStr.GetChar(0) == wxT(':'))) { lineStr = lineStr.AfterFirst(wxT(':')); if (lineStr.IsEmpty() || lineStr.BeforeFirst(wxT(':')).ToLong(&line)) break; } } event.m_commandInt = (int)line; luaInterpreter->SendEvent( event ); } return 0; } void LuaDebugHook(lua_State *L, lua_Debug *LDebug) { wxLuaInterpreter *luaInterpreter = wxFindLuaInterpreter(L); // during program shutdown this can be called - ignore it if (luaInterpreter == NULL) return; // FIXME - for select event types we don't want to do anything wxEventType evtType = luaInterpreter->GetStateVariables()->m_inEventType; if ((evtType != -1)) //(evtType == wxEVT_IDLE) && (evtType == wxEVT_PAINT) && //(evtType == wxEVT_DESTROY) && (evtType == wxEVT_CLOSE_WINDOW)) return; // they want to break the program, restore old debug hook, then error out if (luaInterpreter->GetBreak()) { // restore hook to previous state see wxLuaInterpreter::Break() luaInterpreter->SetLuaDebugHook(luaInterpreter->GetLuaDebugHookCount(), luaInterpreter->GetLuaDebugHookYield(), luaInterpreter->GetLuaDebugHookSendEvt(), luaInterpreter->GetLuaDebugHook()); terror(L, wx2lua(luaInterpreter->GetBreakMessage())); return; } if (luaInterpreter->GetLuaDebugHookSendEvt()) { int ret = 0; ret = lua_getinfo(L, "l", LDebug); // line (ldebug.currentline) wxLuaEvent event(wxEVT_LUA_DEBUG_HOOK, luaInterpreter->GetId(), luaInterpreter); event.m_lua_Debug = LDebug; event.m_commandInt = LDebug->currentline; luaInterpreter->SendEvent( event ); if (event.m_stop_interpreter) terror(L, "Interpreter stopped"); } // Try to yield *after* sending event to allow C++ gui update if (luaInterpreter->GetLuaDebugHookYield() > 0) { // yield based on number of ms passed NOT every hook event unsigned long last_time = luaInterpreter->GetLastLuaDebugHookTime(); unsigned long cur_time = wxGetLocalTimeMillis().GetLo(); if ((cur_time > last_time + luaInterpreter->GetLuaDebugHookYield()) || (cur_time < last_time)) // wrapped { luaInterpreter->SetLastLuaDebugHookTime( cur_time ); wxYieldIfNeeded(); } } } //----------------------------------------------------------------------------- // wxLuaEvent //----------------------------------------------------------------------------- DEFINE_LOCAL_EVENT_TYPE(wxEVT_LUA_CREATION) DEFINE_LOCAL_EVENT_TYPE(wxEVT_LUA_CONSOLE) DEFINE_LOCAL_EVENT_TYPE(wxEVT_LUA_WARNING) DEFINE_LOCAL_EVENT_TYPE(wxEVT_LUA_ERROR) DEFINE_LOCAL_EVENT_TYPE(wxEVT_LUA_DEBUG_HOOK) DEFINE_LOCAL_EVENT_TYPE(wxEVT_LUA_SHUTDOWN) wxLuaEvent::wxLuaEvent(wxEventType commandType, int id, wxLuaInterpreter *interpreter) : wxNotifyEvent(commandType, id) { m_luaInterpreter = interpreter; m_lua_Debug = NULL; m_stop_interpreter = FALSE; } //----------------------------------------------------------------------------- // wxLuaInterpreter //----------------------------------------------------------------------------- IMPLEMENT_ABSTRACT_CLASS(wxLuaInterpreter, wxObject) wxLuaInterpreter::wxLuaInterpreter() : wxObject() { Init(); } wxLuaInterpreter::wxLuaInterpreter(wxEvtHandler *handler, int id) : wxObject() { Init(); Create(handler, id); } void wxLuaInterpreter::Init() { #ifdef WXLUA_THREAD_INTERCEPTION setupthreadhandlers(); #endif //WXLUA_THREAD_INTERCEPTION m_is_running = FALSE; m_user_break = FALSE; m_last_debug_hook_time = wxGetLocalTimeMillis().GetLo(); m_id = wxID_ANY; m_evtHandler = NULL; m_lua_State = NULL; m_luaAllocated = false; m_luaStateVariables = NULL; m_lua_debug_hook_count = 100; m_lua_debug_hook_yield = 50; m_lua_debug_hook_send_evt = FALSE; m_lua_debug_hook = 0; } bool wxLuaInterpreter::Create(lua_State *inL, wxEvtHandler *handler, int id) { if (Ok() && !Destroy()) return FALSE; m_luaStateVariables = new wxLuaStateVariables; m_evtHandler = handler; m_id = id; // create a lua instance if (inL != NULL) { m_lua_State = inL; m_luaAllocated = false; } else { m_lua_State = lua_open(); m_luaAllocated = true; } lua_State *L = m_lua_State; // load some useful libraries luaopen_base(L); luaopen_table(L); luaopen_string(L); luaopen_math(L); luaopen_debug(L); luaopen_io(L); luaopen_loadlib(L); s_wxHashMapLuaInterpreter[L] = this; // Stick us into the lua interpreter - push key, value lua_pushstring( L, "__wxLuaInterpreter" ); lua_pushlightuserdata( L, (void*)this ); // set the value lua_settable( L, LUA_REGISTRYINDEX ); // register handlers to send events if (m_luaAllocated) { RegisterFunction(LuaPrint, wxT("print")); RegisterFunction(LuaAlert, wxT("_ALERT")); RegisterFunction(LuaTraceback, wxT("_TRACEBACK")); } // Load the wxWidgets libraries RegisterWxLua(L); // alert people that we've been created so they can finish setting us up wxLuaEvent event(wxEVT_LUA_CREATION, GetId(), this); SendEvent( event ); return TRUE; } wxLuaInterpreter::~wxLuaInterpreter() { if (Ok()) { m_evtHandler = NULL; // no events here, the handler may already be gone Destroy(TRUE); } delete m_luaStateVariables; } bool wxLuaInterpreter::Destroy(bool force) { wxCHECK_MSG(Ok(), FALSE, wxT("Interpreter not created")); wxCHECK_MSG(!m_is_running, FALSE, wxT("Interpreter still running, can't destroy")); // remove deleted windows first if (m_luaStateVariables->m_pWindowList && m_luaStateVariables->m_pWindowList->GetCount()) wxLuaCleanupWindows(m_luaStateVariables->m_pWindowList, TRUE); // are there still windows? ask to abort deleting them if !force if (m_luaStateVariables->m_pWindowList && m_luaStateVariables->m_pWindowList->GetCount()) { int ret = wxOK; if (!force) { ret = wxMessageBox(wxT("Windows are still open, would you like to delete them?"), wxT("Delete existing windows?"), wxOK|wxCANCEL|wxICON_QUESTION); } if (ret == wxCANCEL) return FALSE; wxPrintf(wxT("Deleting windows\n")); // delete windows and their eventhandler since they delete the LuaCallbacks // which require a lua_State wxLuaCleanupWindows(m_luaStateVariables->m_pWindowList, FALSE); // wait for wxWindow::Destroy() to really delete the windows //wxYieldIfNeeded(); } CleanupWxLua(m_lua_State, m_luaAllocated); s_wxHashMapLuaInterpreter.erase(m_lua_State); delete m_luaStateVariables; m_luaStateVariables = NULL; m_lua_State = NULL; m_evtHandler = NULL; return TRUE; } bool wxLuaInterpreter::Ok() const { return m_lua_State != NULL; } void wxLuaInterpreter::SetEventHandler(wxEvtHandler *evtHandler) { m_evtHandler = evtHandler; } wxEvtHandler *wxLuaInterpreter::GetEventHandler() const { return m_evtHandler; } void wxLuaInterpreter::SetId(int id) { m_id = id; } int wxLuaInterpreter::GetId() const { return m_id; } int wxLuaInterpreter::RunFile(const wxString &filename) { wxCHECK_MSG(Ok(), -1, wxT("lua interpreter not created")); wxCHECK_MSG(!m_is_running, -1, wxT("lua interpreter is already running")); m_user_break = FALSE; m_is_running = TRUE; // int ret_val = lua_dofile(m_lua_State, wx2lua(filename)); int ret_val = LuaDoFile(m_lua_State, filename); // FIXME use LuaDoFile in RunFile ? m_is_running = FALSE; if (!m_user_break) (void)CheckRunError(ret_val); m_user_break = FALSE; return ret_val; } int wxLuaInterpreter::RunString(const wxString &script, const wxString& WXUNUSED(name)) { wxCHECK_MSG(Ok(), -1, wxT("lua interpreter not created")); wxCHECK_MSG(!m_is_running, -1, wxT("lua interpreter is already running")); m_user_break = FALSE; #ifdef __WXMSW__ // FIXME - hack for \ getting stripped out by lua wxString s; size_t len = script.Length(); for (size_t n = 0; n < len; n++) { s += script.GetChar(n); if (script.GetChar(n) == wxT('\\')) s += wxT("\\"); } #else wxString s = script; #endif // This is simple code to run the string, it calls _ALERT function on error m_is_running = TRUE; //int ret_val = luaL_loadbuffer(m_lua_State, wx2lua(s), s.Len(), wx2lua(name)); int ret_val = lua_dostring(m_lua_State, wx2lua(s)); m_is_running = FALSE; // if it's been stopped then don't send this error message, already sent stopped one if (!m_user_break) (void)CheckRunError(ret_val); m_user_break = FALSE; return ret_val; } int wxLuaInterpreter::RunBuffer(const unsigned char buf[], size_t size, const wxString &name) { wxCHECK_MSG(Ok(), -1, wxT("lua interpreter not created")); wxCHECK_MSG(!m_is_running, -1, wxT("lua interpreter is already running")); m_user_break = FALSE; m_is_running = TRUE; //int ret_val = luaL_loadbuffer(m_lua_State, wx2lua(script), script.Len(), "=hello"); int ret_val = lua_dobuffer(m_lua_State, (const char*)buf, size, wx2lua(name)); m_is_running = FALSE; if (!m_user_break) (void)CheckRunError(ret_val); m_user_break = FALSE; return ret_val; } bool wxLuaInterpreter::IsRunning() const { return m_is_running; } void wxLuaInterpreter::Break(const wxString &msg) { wxCHECK_RET(Ok(), wxT("lua interpreter not created")); wxCHECK_RET(m_is_running, wxT("lua interpreter not running")); // Lua likes to be stopped within the debug hook, you get funny wxYield // recursion asserts if you call terror() within another wxYield, ie. from a gui button m_break_msg = msg; m_user_break = TRUE; SetLuaDebugHook(1, -1, FALSE); m_is_running = FALSE; } bool wxLuaInterpreter::GetBreak() const { return m_user_break; } wxString wxLuaInterpreter::GetBreakMessage() const { return m_break_msg; } void wxLuaInterpreter::SetLuaDebugHook(int count, int yield, bool send_debug_evt, int hook) { wxCHECK_RET(Ok(), wxT("lua interpreter not created")); m_lua_debug_hook_count = count; m_lua_debug_hook_yield = yield; m_lua_debug_hook_send_evt = send_debug_evt; m_lua_debug_hook = hook; if (count > 0) { // These are the various hooks you can install //LUA_MASKCALL, LUA_MASKRET, LUA_MASKLINE, and LUA_MASKCOUNT //lua_sethook(m_lua_State, LuaDebugHook, LUA_MASKCALL | LUA_MASKLINE | LUA_MASKRET, 0); lua_sethook(m_lua_State, LuaDebugHook, hook, count); } else lua_sethook(m_lua_State, LuaDebugHook, 0, 0); // disable hook } int wxLuaInterpreter::GetLuaDebugHookCount() const { return m_lua_debug_hook_count; } int wxLuaInterpreter::GetLuaDebugHookYield() const { return m_lua_debug_hook_yield; } bool wxLuaInterpreter::GetLuaDebugHookSendEvt() const { return m_lua_debug_hook_send_evt; } int wxLuaInterpreter::GetLuaDebugHook() const { return m_lua_debug_hook; } unsigned long wxLuaInterpreter::GetLastLuaDebugHookTime() const { return m_last_debug_hook_time; } void wxLuaInterpreter::SetLastLuaDebugHookTime(unsigned long t) { m_last_debug_hook_time = t; } lua_State *wxLuaInterpreter::GetLuaState() const { return m_lua_State; } wxLuaStateVariables *wxLuaInterpreter::GetStateVariables() const { return m_luaStateVariables; } void wxLuaInterpreter::RegisterFunction(lua_CFunction func, const wxString &funcName) { wxCHECK_RET(Ok(), wxT("lua interpreter not created")); lua_register( GetLuaState(), wx2lua(funcName), func ); } void wxLuaInterpreter::DisplayError( const wxString &errorMsg ) { wxLuaEvent event(wxEVT_LUA_ERROR, GetId(), this); event.SetString(errorMsg); SendEvent( event ); } bool wxLuaInterpreter::CheckRunError(int rc) { wxString msg; if (!wxLuaCheckRunError(rc, &msg)) { wxLuaEvent event(wxEVT_LUA_ERROR, GetId(), this); event.SetString(msg); event.m_commandInt = -1; // don't know what line the error occured SendEvent( event ); return FALSE; } return TRUE; } void wxLuaInterpreter::SendEvent( wxLuaEvent &event ) const { if (GetEventHandler()) { event.SetEventObject( (wxObject*)this ); GetEventHandler()->ProcessEvent(event); } } --- NEW FILE: internal.cpp --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Stuff to setup wxLua in a lua_State // Author: J Winwood // Created: 14/11/2001 // Modifications: Type checking added when accessing user data items // Support for wxWidgets 2.3 // Thanks to Francis Irving for separating out into // Library and Standalone modules. // The number of non-wxObject class encapsulations was getting // out of hand! Reimplemented using preprocessor macros. // Added code to reset the metatable of objects when they are // deleted (in the C++ sense) so that method calls can not be // made on deleted objects. Applies to wxWindow-derived objects // only. // Copyright: (c) 2001-2003 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) [...2181 lines suppressed...] return false; case LUA_ERRSYNTAX: if (msg) *msg = wxT("wxLua: Syntax error during pre-compilation"); return false; case LUA_ERRMEM: if (msg) *msg = wxT("wxLua: Memory allocation error"); return false; case LUA_ERRERR: if (msg) *msg = wxT("wxLua: Generic error or an error occurred while running the error handler"); return false; case LUA_ERRFILE: if (msg) *msg = wxT("wxLua: Error occurred while opening file"); return false; default : if (msg) *msg = wxT("wxLua: Unknown error"); break; } return false; } --- NEW FILE: library.cpp --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Implements wxLuaApp and the wxGetBaseApp function // Author: J Winwood // Created: 14/11/2001 // Modifications: Thanks to Francis Irving for separating out into // Library and Standalone modules. // Copyright: (c) 2002 Creature Labs. All rights reserved. // Copyright: (c) 2001-2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "library.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wxlua/library.h" #include "wxlua/internal.h" #include "wxlua/dserver.h" // ---------------------------------------------------------------------------- // wxLuaHandler - Allow for Custom Lua Handler (an alternative to wxLuaApp) // ---------------------------------------------------------------------------- wxLuaHandler* wxLuaHandler::sm_luahandler = NULL; wxLuaHandler::wxLuaHandler() { wxASSERT(!sm_luahandler); sm_luahandler = this; } wxLuaHandler::~wxLuaHandler() { sm_luahandler = NULL; } wxLuaHandler& wxGetLuaHandler() { return *wxLuaHandler::sm_luahandler; } |
From: John L. <jr...@us...> - 2005-06-06 23:06:33
|
Update of /cvsroot/wxlua/wxLua/modules/wxluasocket/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/wxluasocket/src Added Files: debugio.cpp dserver.cpp dtarget.cpp socket.cpp Log Message: moved files to the modules directory structure --- NEW FILE: dtarget.cpp --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Implements the client end of wxLua debugging session // Author: J. Winwood // Created: May 2002 // RCS-ID: $Id: dtarget.cpp,v 1.1 2005/06/06 23:06:20 jrl1 Exp $ // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "dtarget.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif [...1091 lines suppressed...] lua_pushvalue(L, idx); /* value to print */ lua_call(L, 1, 1); wxString s = lua2wx(lua_tostring(L, -1)); /* get result */ if (s.IsEmpty()) return luaL_error(L, "`tostring' must return a string to `print'"); if (idx > 1) stream.Append(wxT("\t")); stream.Append(s); lua_pop(L, 1); /* pop result */ } lua_getglobal(L, debugName); LuaDebugTarget *pTarget = (LuaDebugTarget *) lua_touserdata(L, -1); lua_pop(L, 1); if (pTarget != NULL) pTarget->NotifyPrint(stream); return 0; } --- NEW FILE: dserver.cpp --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaDebugServer.cpp // Purpose: Provide remote debugging support for wxLua. // Author: J. Winwood // Created: May 2002. // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "dserver.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/thread.h" #include "wxlua/internal.h" #include "wxlua/library.h" #include "wxlua/dserver.h" #if wxCHECK_VERSION(2, 3, 0) #include "wxlua/staktree.h" #endif wxString g_strProgramName; wxString g_strNetworkName; // ---------------------------------------------------------------------------- // wxLuaDebugServer // ---------------------------------------------------------------------------- IMPLEMENT_CLASS(wxLuaDebugServer, wxLuaDebuggerBase) wxLuaDebugServer::wxLuaDebugServer(int portNumber) : m_serverSocket(NULL), m_acceptedSocket(NULL), m_processID(-1), m_portNumber(portNumber), m_pProcess(NULL), m_pThread(NULL), m_pStackFrameDialog(NULL), m_fShutdown(false) { StartServer(); } bool wxLuaDebugServer::StartServer() { m_serverSocket = new wxLuaSocket; if (m_serverSocket != NULL) { try { // listen on the specified port m_serverSocket->Listen(m_portNumber); } catch(wxLuaSocketException & e) { NotifyError(wxString::Format(_("Error while opening listening socket. %s"), e.description().c_str())); m_fShutdown = true; } } return (m_serverSocket != NULL); } bool wxLuaDebugServer::StartClient() { if ((m_pProcess == NULL) && StartServerThread()) { m_pProcess = new wxProcess(); wxString command = wxString::Format(wxT("%s -d%s:%u"), g_strProgramName.c_str(), #ifdef __WXMSW__ g_strNetworkName.c_str(), #else wxT("localhost"), #endif m_portNumber); m_processID = wxExecute(command, FALSE, m_pProcess); return (m_processID != -1); } return false; } bool wxLuaDebugServer::StartServerThread() { if (!m_fShutdown) { m_pThread = new wxLuaThread(this); return ((m_pThread != NULL) && (m_pThread->Create() == wxTHREAD_NO_ERROR) && (m_pThread->Run() == wxTHREAD_NO_ERROR)); } return false; } bool wxLuaDebugServer::StopServer() { // Set the shutdown flag m_fShutdown = true; // close the session socket if (m_acceptedSocket != NULL) { try { m_acceptedSocket->Shutdown(SD_BOTH); } catch(wxLuaSocketException & /*e*/) { NotifyError(_("Error while shutting down session socket")); } wxUsleep(100); wxLuaSocket *acceptedSocket = m_acceptedSocket; m_acceptedSocket = NULL; delete acceptedSocket; } // close the server socket if (m_serverSocket != NULL) { // close the server socket by connecting // to the socket, thus completing the // 'accept'. If a client has not connected, // this code will satisfy the accept // the m_fShutdown flag will be set // so the thread will not loop and instead // will just destroy the session socket // object and return. try { wxLuaSocket closeSocket; #ifdef __WXMSW__ closeSocket.Connect(g_strNetworkName, m_portNumber); #else closeSocket.Connect(wxT("localhost"), m_portNumber); #endif closeSocket.Shutdown(SD_BOTH); wxUsleep(100); wxLuaSocket *serverSocket = m_serverSocket; m_serverSocket = NULL; delete serverSocket; } catch(wxLuaSocketException & /*e*/) { NotifyError(_("Error while shutting down server socket")); } } // One of the above two operations // terminates the thread. // Wait for it to stop. if (m_pThread != NULL) m_pThread->Wait(); return true; } wxLuaDebugServer::~wxLuaDebugServer() { StopServer(); if (m_pThread != NULL) delete m_pThread; #if wxCHECK_VERSION(2, 3, 0) if (m_pProcess != NULL && m_processID != -1) m_pProcess->Kill(m_processID, wxSIGKILL); #endif } bool wxLuaDebugServer::AddBreakPoint(const wxString &fileName, int lineNumber) { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_ADD_BREAKPOINT) && WriteString(m_acceptedSocket, fileName) && WriteInt(m_acceptedSocket, lineNumber)) { return true; } } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::RemoveBreakPoint(const wxString &fileName, int lineNumber) { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_REMOVE_BREAKPOINT) && WriteString(m_acceptedSocket, fileName) && WriteInt(m_acceptedSocket, lineNumber)) { return true; } } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::ClearAllBreakPoints() { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_CLEAR_ALL_BREAKPOINTS)) return true; } catch(wxLuaSocketException & /*e*/) { } } return false; } void wxLuaDebugServer::NotifyError(const wxString &msg) { wxLuaDebugEvent debugEvent(wxEVT_DEBUG_ERROR); debugEvent.SetMessage(msg); wxGetLuaHandler().AddPendingEvent(debugEvent); } bool wxLuaDebugServer::Compile(const wxString &fileName, const wxString &buffer) { bool fErrorsSeen = false; lua_State *luaState = lua_open(); luaopen_base(luaState); luaopen_table(luaState); luaopen_string(luaState); luaopen_math(luaState); luaopen_debug(luaState); luaopen_io(luaState); luaopen_loadlib(luaState); LuaCharBuffer charbuf(buffer); int status = luaL_loadbuffer(luaState, charbuf.GetData(), charbuf.Length(), wx2lua(fileName)); switch (status) { case LUA_ERRRUN: NotifyError(_("Error while compiling chunk\n")); fErrorsSeen = true; break; case LUA_ERRSYNTAX: { wxString strError(_("Syntax error during pre-compilation: ")); strError += lua2wx(lua_tostring(luaState, -1)); strError += wxT("\n"); NotifyError(strError); } fErrorsSeen = true; break; case LUA_ERRMEM: NotifyError(_("Memory allocation error\n")); fErrorsSeen = true; break; case LUA_ERRERR: NotifyError(_("Generic error or an error occurred while running the error handler\n")); fErrorsSeen = true; break; case LUA_ERRFILE: { wxString strError(_("Error occurred while opening file: ")); strError += lua2wx(lua_tostring(luaState, -1)); strError += wxT("\n"); NotifyError(strError); } fErrorsSeen = true; break; default: NotifyError(_("Compiled OK\n")); break; } lua_close(luaState); return !fErrorsSeen; } bool wxLuaDebugServer::Run(const wxString &fileName, const wxString &buffer) { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_RUN_BUFFER) && WriteString(m_acceptedSocket, fileName) && WriteString(m_acceptedSocket, buffer)) { return true; } } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::Step() { if (m_acceptedSocket != NULL) { try { return WriteByte(m_acceptedSocket, CMD_DEBUG_STEP); } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::StepOver() { if (m_acceptedSocket != NULL) { try { return WriteByte(m_acceptedSocket, CMD_DEBUG_STEPOVER); } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::StepOut() { if (m_acceptedSocket != NULL) { try { return WriteByte(m_acceptedSocket, CMD_DEBUG_STEPOUT); } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::Continue() { if (m_acceptedSocket != NULL) { try { return WriteByte(m_acceptedSocket, CMD_DEBUG_CONTINUE); } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::Break() { if (m_acceptedSocket != NULL) { try { return WriteByte(m_acceptedSocket, CMD_DEBUG_BREAK); } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::EnumerateStack() { if (m_acceptedSocket != NULL) { try { return WriteByte(m_acceptedSocket, CMD_ENUMERATE_STACK); } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::Reset() { if (m_acceptedSocket != NULL) { try { return WriteByte(m_acceptedSocket, CMD_RESET); } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::EnumerateStackEntry(int stackEntry) { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_ENUMERATE_STACK_ENTRY) && WriteInt(m_acceptedSocket, stackEntry)) { return true; } } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::EnumerateTable(int tableRef, int nIndex, int nItemNode) { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_ENUMERATE_TABLE_REF) && WriteInt(m_acceptedSocket, tableRef) && WriteInt(m_acceptedSocket, nIndex) && WriteInt(m_acceptedSocket, nItemNode)) { return true; } } catch(wxLuaSocketException & /*e*/) { } } return false; } bool wxLuaDebugServer::CleanupDebugReferences() { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_CLEAR_DEBUG_REFERENCES)) { return true; } } catch(wxLuaSocketException & /*e*/) { } } return false; } void *wxLuaThread::Entry() { m_pServer->ThreadFunction(); return 0; } void wxLuaDebugServer::ThreadFunction() { try { m_acceptedSocket = new wxLuaSocket(m_serverSocket->Accept()); if (m_acceptedSocket != NULL) { wxLuaSocket *serverSocket = m_serverSocket; m_serverSocket = NULL; delete serverSocket; #if wxCHECK_VERSION(2, 3, 3) wxUsleep(500); // why ?? #endif // if not shutdown requested if (!m_fShutdown) { try { // Notify that a client has connected and we are ready to debug wxLuaDebugEvent debugEvent(wxEVT_DEBUG_CLIENT_CONNECTED); wxGetLuaHandler().AddPendingEvent(debugEvent); // Enter the debug loop while (!m_fShutdown) { int debugEvent = ReadByte(m_acceptedSocket); switch((debugEvents) debugEvent) { case EVENT_DEBUG_BREAK: { wxString fileName = ReadString(m_acceptedSocket); int lineNumber = ReadInt(m_acceptedSocket); wxLuaDebugEvent debugEvent(wxEVT_DEBUG_BREAK, lineNumber, fileName); wxGetLuaHandler().AddPendingEvent(debugEvent); } break; case EVENT_DEBUG_PRINT: { wxString strMessage = ReadString(m_acceptedSocket); wxLuaDebugEvent debugEvent(wxEVT_DEBUG_PRINT); debugEvent.SetMessage(strMessage); wxGetLuaHandler().AddPendingEvent(debugEvent); } break; case EVENT_DEBUG_ERROR: { wxString strMessage = ReadString(m_acceptedSocket); wxLuaDebugEvent debugEvent(wxEVT_DEBUG_ERROR); debugEvent.SetMessage(strMessage); wxGetLuaHandler().AddPendingEvent(debugEvent); } break; case EVENT_DEBUG_EXIT: { wxLuaDebugEvent debugEvent(wxEVT_DEBUG_EXIT); wxGetLuaHandler().AddPendingEvent(debugEvent); m_fShutdown = true; } break; case EVENT_DEBUG_STACK_ENUM: { wxLuaDebugEvent debugEvent(wxEVT_DEBUG_STACK_ENUM); wxLuaDebugData *pDebugData = ReadDebugData(m_acceptedSocket); if (pDebugData != NULL) debugEvent.SetDebugData(-1, pDebugData); wxGetLuaHandler().AddPendingEvent(debugEvent); } break; case EVENT_DEBUG_STACK_ENTRY_ENUM: { wxLuaDebugEvent debugEvent(wxEVT_DEBUG_STACK_ENTRY_ENUM); int stackRef = ReadInt(m_acceptedSocket); wxLuaDebugData *pDebugData = ReadDebugData(m_acceptedSocket); if (pDebugData != NULL) debugEvent.SetDebugData(stackRef, pDebugData); wxGetLuaHandler().AddPendingEvent(debugEvent); } break; case EVENT_DEBUG_TABLE_ENUM: { wxLuaDebugEvent debugEvent(wxEVT_DEBUG_TABLE_ENUM); int itemNode = ReadInt(m_acceptedSocket); wxLuaDebugData *pDebugData = ReadDebugData(m_acceptedSocket); if (pDebugData != NULL) debugEvent.SetDebugData(itemNode, pDebugData); wxGetLuaHandler().AddPendingEvent(debugEvent); } break; case EVENT_DEBUG_EVALUATE_EXPR: { wxLuaDebugEvent debugEvent(wxEVT_DEBUG_EVALUATE_EXPR); int exprRef = ReadInt(m_acceptedSocket); wxString strResult = ReadString(m_acceptedSocket); debugEvent.SetMessage(strResult); debugEvent.SetDebugData(exprRef); wxGetLuaHandler().AddPendingEvent(debugEvent); } break; case EVENT_DEBUG_BREAKPOINT_ADDED : break; // FIXME - unused case EVENT_DEBUG_BREAKPOINT_REMOVED : break; // FIXME - unused } } } catch(wxLuaSocketException & /*e*/) { } } // delete the accepted socket if (m_acceptedSocket != NULL) { wxLuaSocket *acceptedSocket = m_acceptedSocket; m_acceptedSocket = NULL; delete acceptedSocket; } } } catch(wxLuaSocketException & /*e*/) { } } void wxLuaThread::OnExit() { } #if wxCHECK_VERSION(2, 3, 0) bool wxLuaDebugServer::DisplayStackDialog(wxWindow *pParent) { if (m_pStackFrameDialog == NULL) { m_pStackFrameDialog = new wxLuaStackFrame(pParent, _("Stack frame"), wxDefaultPosition, wxSize(500, 250), this); m_pStackFrameDialog->ShowModal(); m_pStackFrameDialog->Destroy(); m_pStackFrameDialog = NULL; return true; } return false; } #endif bool wxLuaDebugServer::EvaluateExpr(int exprRef, const wxString &strExpression) { if (m_acceptedSocket != NULL) { try { if (WriteByte(m_acceptedSocket, CMD_EVALUATE_EXPR) && WriteInt(m_acceptedSocket, exprRef) && WriteString(m_acceptedSocket, strExpression)) { return true; } } catch(wxLuaSocketException & /*e*/) { } } return false; } --- NEW FILE: socket.cpp --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaSocket.cpp // Purpose: Socket class for wxLua. // Author: J. Winwood // Created: February 2002 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "socket.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wxlua/socket.h" #ifdef _MSC_VER #pragma warning(push, 4) #endif extern const wxCharBuffer wx2lua(const wxString& AppString); extern wxString lua2wx(const char * wx2lua); // ---------------------------------------------------------------------------- // wxLuaSocket // ---------------------------------------------------------------------------- // Default socket constructor. wxLuaSocket::wxLuaSocket() : m_sockstate(SOCKET_CLOSED) { } // Socket constructor from an accepted socket wxLuaSocket::wxLuaSocket(const wxLuaSocket::wxLuaAcceptedSocket &acceptedSocket) : m_sock(acceptedSocket.m_sock), m_sockaddress(acceptedSocket.m_addr), m_sockstate(SOCKET_ACCEPTED) { } // Accepted socket constructor wxLuaSocket::wxLuaAcceptedSocket::wxLuaAcceptedSocket(socket_type sock, sockaddr_in addr) : m_sock(sock), m_addr(addr) { } // socket destructor: close the socket if not already closed. wxLuaSocket::~wxLuaSocket() { if (m_sockstate != SOCKET_CLOSED) { #ifdef WIN32 ::closesocket(m_sock); #else ::close(m_sock); #endif } } // Create a listening socket, using the specified port number void wxLuaSocket::Listen(u_short portNumber, int backLog) { if (m_sockstate != SOCKET_CLOSED) throw wxLuaSocketException(wxLuaSocketException::SOCKET_NOT_CLOSED); m_sock = ::socket(AF_INET, SOCK_STREAM, 0); if (m_sock == INVALID_SOCKET) throw wxLuaSocketException(wxLuaSocketException::SOCKET_INVALID_SOCKET); sockaddr_in localAddr = { 0 }; localAddr.sin_family = AF_INET; localAddr.sin_port = htons(portNumber); localAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (::bind(m_sock, (sockaddr *) &localAddr, sizeof(localAddr)) == SOCKET_ERROR) throw wxLuaSocketException(wxLuaSocketException::SOCKET_BIND_FAILED); if (::listen(m_sock, backLog) == SOCKET_ERROR) throw wxLuaSocketException(wxLuaSocketException::SOCKET_LISTEN_FAILED); memset(&m_sockaddress, 0, sizeof(m_sockaddress)); m_sockstate = SOCKET_LISTENING; } // Accept a connection, returning an accepted socket. wxLuaSocket::wxLuaAcceptedSocket wxLuaSocket::Accept() { if (m_sockstate != SOCKET_LISTENING) throw wxLuaSocketException(wxLuaSocketException::SOCKET_NOT_LISTENING); sockaddr_in fromAddr = { 0 }; socklen_t length = sizeof(fromAddr); socket_type acceptedSocket = ::accept(m_sock, (sockaddr *)&fromAddr, &length); if (acceptedSocket == INVALID_SOCKET) throw wxLuaSocketException(wxLuaSocketException::SOCKET_ACCEPT_FAILED); return wxLuaAcceptedSocket(acceptedSocket, fromAddr); } // Connect to a given host and port number void wxLuaSocket::Connect(const wxString &addr, u_short portNumber) { hostent *pHost = NULL; if (m_sockstate != SOCKET_CLOSED) throw wxLuaSocketException(wxLuaSocketException::SOCKET_NOT_CLOSED); m_sock = ::socket(AF_INET, SOCK_STREAM, 0); if (m_sock == INVALID_SOCKET) throw wxLuaSocketException(wxLuaSocketException::SOCKET_INVALID_SOCKET); unsigned long address = ::inet_addr(wx2lua(addr)); if (address != INADDR_NONE) pHost = ::gethostbyaddr((const char*) &address, 4, AF_INET); else pHost = ::gethostbyname(wx2lua(addr)); if (pHost == NULL) throw wxLuaSocketException(wxLuaSocketException::SOCKET_ADDRESS_NOT_RESOLVED); if (pHost->h_addrtype != AF_INET) throw wxLuaSocketException(wxLuaSocketException::SOCKET_INCOMPATIBLE_TYPE); memset(&m_sockaddress, 0, sizeof(m_sockaddress)); memcpy(&(m_sockaddress.sin_addr), pHost->h_addr_list[0], pHost->h_length); m_sockaddress.sin_family = AF_INET; m_sockaddress.sin_port = htons(portNumber); if (::connect(m_sock, (sockaddr *) &m_sockaddress, sizeof(m_sockaddress)) == SOCKET_ERROR) throw wxLuaSocketException(wxLuaSocketException::SOCKET_CONNECT_FAILED); m_sockstate = SOCKET_CONNECTED; } // Get the address of an open socket wxString wxLuaSocket::GetAddress() const { if (m_sockstate != SOCKET_CONNECTED && m_sockstate != SOCKET_ACCEPTED) throw wxLuaSocketException(wxLuaSocketException::SOCKET_NOT_CONNECTED); return lua2wx(inet_ntoa(m_sockaddress.sin_addr)); } // Get the port number of an open socket int wxLuaSocket::GetPort() const { if (m_sockstate != SOCKET_CONNECTED && m_sockstate != SOCKET_ACCEPTED) throw wxLuaSocketException(wxLuaSocketException::SOCKET_NOT_CONNECTED); return ntohs(m_sockaddress.sin_port); } // Write data to an open socket, repeat until all data has been sent. void wxLuaSocket::Write(const char *buffer, int length) { if (m_sockstate != SOCKET_CONNECTED && m_sockstate != SOCKET_ACCEPTED) throw wxLuaSocketException(wxLuaSocketException::SOCKET_NOT_CONNECTED); while (length > 0) { int numWritten = ::send(m_sock, buffer, length, 0); if (numWritten == SOCKET_ERROR) throw wxLuaSocketException(wxLuaSocketException::SOCKET_SEND_FAILED); length -= numWritten; buffer += numWritten; } } // Read data from an open socket, repeat reading until all data has been read int wxLuaSocket::Read(char *buffer, int length) { if (m_sockstate != SOCKET_CONNECTED && m_sockstate != SOCKET_ACCEPTED) throw wxLuaSocketException(wxLuaSocketException::SOCKET_NOT_CONNECTED); while (length > 0) { int numRead = ::recv(m_sock, buffer, length, 0); if (numRead == 0) return length; if (numRead == SOCKET_ERROR) throw wxLuaSocketException(wxLuaSocketException::SOCKET_RECEIVE_FAILED); length -= numRead; buffer += numRead; } return 0; } // Shutdown a socket in an orderly fashion void wxLuaSocket::Shutdown(int how) { if (m_sockstate != SOCKET_CLOSED) { ::shutdown(m_sock, how); } } // Close an open socket void wxLuaSocket::Close() { if (m_sockstate != SOCKET_CLOSED) { #ifdef WIN32 if (::closesocket(m_sock) == SOCKET_ERROR) throw wxLuaSocketException(wxLuaSocketException::SOCKET_CLOSE_FAILED); #else if (::close(m_sock)) throw wxLuaSocketException(wxLuaSocketException::SOCKET_CLOSE_FAILED); #endif m_sockstate = SOCKET_CLOSED; } } --- NEW FILE: debugio.cpp --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaDebugIO.cpp // Purpose: Debugging I/O functions for wxLua // Author: J. Winwood // Created: May 2002 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "debugio.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wxlua/debugio.h" #include "wxlua/internal.h" #include "wxlua/debug.h" #include "wxlua/socket.h" // ---------------------------------------------------------------------------- // wxLuaDebugIO // ---------------------------------------------------------------------------- unsigned char wxLuaDebugIO::ReadByte(wxLuaSocket *pSocket) { unsigned char value; pSocket->Read((char *) &value, sizeof(value)); return value; } short wxLuaDebugIO::ReadWord(wxLuaSocket *pSocket) { short value; pSocket->Read((char *)&value, sizeof(value)); return value; } unsigned short wxLuaDebugIO::ReadUWord(wxLuaSocket *pSocket) { unsigned short value; pSocket->Read((char *)&value, sizeof(value)); return value; } int wxLuaDebugIO::ReadInt(wxLuaSocket *pSocket) { int value; pSocket->Read((char *) &value, sizeof(value)); return value; } unsigned int wxLuaDebugIO::ReadUInt(wxLuaSocket *pSocket) { unsigned int value; pSocket->Read((char *) &value, sizeof(value)); return value; } long wxLuaDebugIO::ReadLong(wxLuaSocket *pSocket) { long value; pSocket->Read((char *) &value, sizeof(value)); return value; } unsigned long wxLuaDebugIO::ReadULong(wxLuaSocket *pSocket) { unsigned long value; pSocket->Read((char *) &value, sizeof(value)); return value; } wxString wxLuaDebugIO::ReadString(wxLuaSocket *pSocket) { wxString value; unsigned int length = ReadInt(pSocket); if (length > 0) { char *buffer = new char[length + 1]; pSocket->Read(buffer, length); buffer[length] = 0; value = lua2wx(buffer); delete[] buffer; } return value; } wxLuaDebugData *wxLuaDebugIO::ReadDebugData(wxLuaSocket *pSocket) { wxLuaDebugData *pSortedList = new wxLuaDebugData(); try { size_t idx, idxMax; pSocket->Read((char *) &idxMax, sizeof(idxMax)); for (idx = 0; idx < idxMax; ++idx) { int bufferLength; pSocket->Read((char *) &bufferLength, sizeof(bufferLength)); if (bufferLength > 0) { char *pBuffer = new char[bufferLength]; char *pMemory = pBuffer; pSocket->Read(pMemory, bufferLength); int nReference = *(int *) pMemory; pMemory += sizeof(int); int nIndex = *(int *) pMemory; pMemory += sizeof(int); bool fExpanded = (0 != *pMemory++); const char *pNamePtr = pMemory; pMemory += strlen(pNamePtr) + 1; const char *pTypePtr = pMemory; pMemory += strlen(pTypePtr) + 1; const char *pValuePtr = pMemory; wxLuaDebugDataItem *pItem = new wxLuaDebugDataItem(lua2wx(pNamePtr), lua2wx(pTypePtr), lua2wx(pValuePtr), wxEmptyString, // FIXME! What goes here!? nReference, nIndex, fExpanded); pSortedList->Add(pItem); delete[] pBuffer; } } } catch(wxLuaSocketException & /*e*/) { delete pSortedList; pSortedList = NULL; } return pSortedList; } bool wxLuaDebugIO::WriteByte(wxLuaSocket *pSocket, unsigned char value) { bool result = false; try { pSocket->Write((const char *) &value, sizeof(value)); result = true; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteWord(wxLuaSocket *pSocket, short value) { bool result = false; try { pSocket->Write((const char *) &value, sizeof(value)); result = true; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteUWord(wxLuaSocket *pSocket, unsigned short value) { bool result = false; try { pSocket->Write((const char *) &value, sizeof(value)); result = true; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteInt(wxLuaSocket *pSocket, int value) { bool result = false; try { pSocket->Write((const char *) &value, sizeof(value)); result = true; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteUInt(wxLuaSocket *pSocket, unsigned int value) { bool result = false; try { pSocket->Write((const char *) &value, sizeof(value)); result = true; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteLong(wxLuaSocket *pSocket, long value) { bool result = false; try { pSocket->Write((const char *) &value, sizeof(value)); result = true; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteULong(wxLuaSocket *pSocket, unsigned long value) { bool result = false; try { pSocket->Write((const char *) &value, sizeof(value)); result = true; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteString(wxLuaSocket *pSocket, const wxString &value) { bool result = FALSE; try { LuaCharBuffer buf(value); int buflen = buf.Length(); pSocket->Write((const char *) &buflen, sizeof(buflen)); if (buflen > 0) { pSocket->Write(buf.GetData(), buflen); } result = TRUE; } catch(wxLuaSocketException & /*e*/) { } return result; } bool wxLuaDebugIO::WriteDebugData(wxLuaSocket *pSocket, const wxLuaDebugData *pSortedList) { bool result = false; size_t idx, idxMax = pSortedList->Count(); pSocket->Write((const char *) &idxMax, sizeof(idxMax)); for (idx = 0; idx < idxMax; ++idx) { try { const wxLuaDebugDataItem *item = pSortedList->Item(idx); int nameLength = item->GetName().Length() + 1; int typeLength = item->GetType().Length() + 1; int valueLength = item->GetValue().Length() + 1; int bufferLength = (2 * sizeof(int)) + sizeof(unsigned char) + nameLength + typeLength + valueLength; unsigned char *pBuffer = new unsigned char[bufferLength]; unsigned char *pMemory = pBuffer; pSocket->Write((const char *) &bufferLength, sizeof(bufferLength)); *(int *) pMemory = item->GetReference(); pMemory += sizeof(int); *(int *) pMemory = item->GetIndex(); pMemory += sizeof(int); *pMemory++ = item->IsExpanded(); memcpy(pMemory, wx2lua(item->GetName()), nameLength); pMemory += nameLength; memcpy(pMemory, wx2lua(item->GetType()), typeLength); pMemory += typeLength; memcpy(pMemory, wx2lua(item->GetValue()), valueLength); pSocket->Write((const char *) pBuffer, bufferLength); delete[] pBuffer; result = true; } catch(wxLuaSocketException & /*e*/) { } if (result == false) break; } return result; } |
From: John L. <jr...@us...> - 2005-06-06 23:06:29
|
Update of /cvsroot/wxlua/wxLua/modules/wxluasocket/include In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/wxluasocket/include Added Files: debugio.h dserver.h dtarget.h socket.h Log Message: moved files to the modules directory structure --- NEW FILE: dtarget.h --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Implements the client end of wxLua debugging session // Author: J. Winwood // Created: May 2002 // RCS-ID: $Id: dtarget.h,v 1.1 2005/06/06 23:06:20 jrl1 Exp $ // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef LUA_DEBUG_TARGET_H #define LUA_DEBUG_TARGET_H #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "dtarget.h" #endif #include "wx/dynarray.h" #include "wxlua/defs.h" #include "wxlua/wxlua.h" #include "wxlua/internal.h" #include "wxlua/library.h" #include "wxlua/debug.h" #include "wxlua/debugio.h" #include "wxlua/socket.h" #include "wxlua/staktree.h" // ---------------------------------------------------------------------------- // LuaDebugTarget - Handles Debugger/Debuggee IO // ---------------------------------------------------------------------------- class LuaDebugTarget : public wxObject, public wxLuaDebugIO { private: class LuaThread : public wxThread { public: LuaThread(LuaDebugTarget *pTarget) : wxThread(wxTHREAD_JOINABLE) { m_pTarget = pTarget; } bool TestDestroy(); protected: // thread execution starts here virtual void *Entry(); // called when the thread exits virtual void OnExit(); private: LuaDebugTarget *m_pTarget; }; class BreakPointObject : public wxObject { public: BreakPointObject(const wxString &fileName, int lineNumber) : m_fileName(fileName), m_lineNumber(lineNumber) { } const wxString &GetFileName() const { return m_fileName; } int GetLineNumber() const { return m_lineNumber; } private: wxString m_fileName; int m_lineNumber; }; public: LuaDebugTarget(lua_State *state, const wxString &serverName, int portNumber); ~LuaDebugTarget(); bool Run(); void Stop(); void ThreadFunction(); void DisplayError(const wxString &strError); protected: enum debugOperations { DEBUG_STEP, DEBUG_STEPOVER, DEBUG_STEPOUT, DEBUG_GO }; lua_State *m_luaState; int m_portNumber; wxString m_serverName; wxSortedArrayString m_breakPointList; #if wxCHECK_VERSION(2, 3, 3) wxMutex m_debugMutex; #endif wxCondition m_debugCondition; wxLuaSocket m_clientSocket; debugOperations m_nextOperation; bool m_forceBreak; bool m_resetRequested; bool m_fConnected; bool m_fRunning; bool m_fStopped; bool m_fErrorsSeen; int m_nFramesUntilBreak; #if wxCHECK_VERSION(2, 3, 3) wxMutex m_runMutex; #endif wxCondition m_runCondition; wxLuaBufferArray m_bufferList; LuaThread *m_pThread; wxArrayInt m_references; void ExitThread(); mutable wxCriticalSection m_breakPointListCriticalSection; bool AddBreakPoint(const wxString &fileName, int lineNumber); bool RemoveBreakPoint(const wxString &fileName, int lineNumber); bool ClearAllBreakPoints(); bool Run(const wxString &fileName, const wxString &buffer); bool Step(); bool StepOver(); bool StepOut(); bool Continue(); bool Break(); bool Reset(); bool EnumerateStack(); bool EnumerateStackEntry(int stackRef); bool EnumerateTable(int tableRef, int nIndex, int itemNode); bool EvaluateExpr(int exprRef, const wxString &strExpr); bool NotifyBreak(const wxString &fileName, int lineNumber); bool NotifyPrint(const wxString &errorMsg); bool NotifyError(const wxString &errorMsg); bool NotifyExit(); bool NotifyStackEnumeration(wxLuaDebugData *pDebugData); bool NotifyStackEntryEnumeration(int stackRef, wxLuaDebugData *pDebugData); bool NotifyTableEnumeration(int itemNode, wxLuaDebugData *pDebugData); bool NotifyEvaluateExpr(int exprRef, const wxString &strResult); bool DebugHook(int event); private: bool WaitForConnect() const; bool AtBreakPoint(const wxString &fileName, int lineNumber) const; wxString GetTableInfo(int index); wxString GetUserDataInfo(int index, bool full = true); wxString MakeBoolean(int num); wxString MakeNumber(double dnum); wxString GetDebugInfo(int &lineNumber) const; static void LUACALL LuaDebugHook(lua_State *state, lua_Debug *debug); static int LUACALL LuaPrint (lua_State *L); }; #endif // LUA_DEBUG_TARGET_H --- NEW FILE: dserver.h --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Implements the debugger end of wxLua debugging session // Author: J. Winwood // Created: May 2002 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef WX_LUA_DEBUG_SERVER_H #define WX_LUA_DEBUG_SERVER_H #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "dserver.h" #endif #include "wx/process.h" #include "wxlua/defs.h" #include "wxlua/socket.h" #include "wxlua/debug.h" #include "wxlua/debugio.h" class WXDLLIMPEXP_WXLUA wxLuaDebugServer; class WXDLLIMPEXP_WXLUA wxLuaDebugEvent; class WXDLLIMPEXP_WXLUA wxLuaStackFrame; WXDLLIMPEXP_DATA_WXLUA(extern wxString) g_strProgramName; WXDLLIMPEXP_DATA_WXLUA(extern wxString) g_strNetworkName; // ---------------------------------------------------------------------------- // wxLuaThread // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaThread : public wxThread { public: wxLuaThread(wxLuaDebugServer *pServer) : wxThread(wxTHREAD_JOINABLE) { m_pServer = pServer; } protected: // thread execution starts here virtual void *Entry(); // called when the thread exits virtual void OnExit(); private: wxLuaDebugServer *m_pServer; }; // ---------------------------------------------------------------------------- // wxLuaDebugServer // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaDebugServer : public wxLuaDebuggerBase, public wxLuaDebugIO { public: wxLuaDebugServer(int portNumber); virtual ~wxLuaDebugServer(); bool StartServer(); bool StopServer(); bool StartClient(); bool StartServerThread(); bool WaitForConnect(int timeOut); bool AddBreakPoint(const wxString &fileName, int lineNumber); bool RemoveBreakPoint(const wxString &fileName, int lineNumber); bool ClearAllBreakPoints(); bool Run(const wxString &fileName, const wxString &buffer); bool Step(); bool StepOver(); bool StepOut(); bool Continue(); bool Break(); bool Reset(); bool EnumerateStack(); bool EnumerateStackEntry(int stackEntry); bool EnumerateTable(int tableRef, int nIndex, int nItemNode); bool CleanupDebugReferences(); void ThreadFunction(); #if wxCHECK_VERSION(2, 3, 0) bool DisplayStackDialog(wxWindow *pParent); #endif bool EvaluateExpr(int exprRef, const wxString &pExpression); static bool Compile(const wxString &fileName, const wxString &buffer); protected: wxLuaSocket *m_serverSocket; wxLuaSocket *m_acceptedSocket; int m_processID; int m_portNumber; wxProcess *m_pProcess; wxLuaThread *m_pThread; wxLuaStackFrame *m_pStackFrameDialog; bool m_fShutdown; private: static void NotifyError(const wxString &msg); static int LuaCompileError (lua_State *L); DECLARE_CLASS(wxLuaDebugServer) }; #endif // WX_LUA_DEBUG_SERVER_H --- NEW FILE: debugio.h --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Implements the debugger end of wxLua debugging session // Author: J. Winwood // Created: April 2002 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef WX_LUA_DEBUG_IO_H #define WX_LUA_DEBUG_IO_H #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "debugio.h" #endif #include "wxlua/defs.h" class WXDLLIMPEXP_WXLUA wxLuaDebugData; class WXDLLIMPEXP_WXLUA wxLuaSocket; // ---------------------------------------------------------------------------- // wxLuaDebugIO // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaDebugIO { protected: unsigned char ReadByte(wxLuaSocket *); short ReadWord(wxLuaSocket *); unsigned short ReadUWord(wxLuaSocket *); int ReadInt(wxLuaSocket *); unsigned int ReadUInt(wxLuaSocket *); long ReadLong(wxLuaSocket *); unsigned long ReadULong(wxLuaSocket *); wxString ReadString(wxLuaSocket *); wxLuaDebugData *ReadDebugData(wxLuaSocket *); bool WriteByte(wxLuaSocket *, unsigned char value); bool WriteWord(wxLuaSocket *, short value); bool WriteUWord(wxLuaSocket *, unsigned short value); bool WriteInt(wxLuaSocket *, int value); bool WriteUInt(wxLuaSocket *, unsigned int value); bool WriteLong(wxLuaSocket *, long value); bool WriteULong(wxLuaSocket *, unsigned long value); bool WriteString(wxLuaSocket *, const wxString &value); bool WriteDebugData(wxLuaSocket *, const wxLuaDebugData *pData); }; #endif // WX_LUA_DEBUG_IO_H --- NEW FILE: socket.h --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaSocket.h // Purpose: wxLua Socket interfaces // Author: J. Winwood // Created: March 2002 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence. ///////////////////////////////////////////////////////////////////////////// #ifndef WX_LUA_SOCKET_H_ #define WX_LUA_SOCKET_H_ #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "socket.h" #endif #include "wxlua/defs.h" #ifdef WIN32 typedef int socklen_t; #include <winsock.h> #else #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <cerrno> #include <netdb.h> #include <arpa/inet.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #endif // !WIN32 #ifndef SD_RECEIVE #define SD_RECEIVE 0 #define SD_SEND 1 #define SD_BOTH 2 #endif // SD_RECEIVE // ---------------------------------------------------------------------------- // wxLuaSocket // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaSocket { #ifdef WIN32 typedef SOCKET socket_type; #else typedef int socket_type; #endif // proxy class for accept class wxLuaAcceptedSocket { public: // constructor wxLuaAcceptedSocket(socket_type socket, sockaddr_in address); wxLuaAcceptedSocket(const wxLuaAcceptedSocket &); wxLuaAcceptedSocket& operator=(const wxLuaAcceptedSocket &); private: socket_type m_sock; sockaddr_in m_addr; friend class wxLuaSocket; }; public: enum SocketState { SOCKET_CLOSED, SOCKET_LISTENING, SOCKET_ACCEPTING, SOCKET_ACCEPTED, SOCKET_CONNECTED, SOCKET_WRITE_BLOCKED }; // constructors wxLuaSocket(); wxLuaSocket(const wxLuaAcceptedSocket &acceptedSocket); // destructor ~wxLuaSocket(); // server: bind and listen for client connections void Listen(u_short port, int backLog = 100); // server: accept a connection from a client wxLuaAcceptedSocket Accept(); // client: connect a client to a server void Connect(const wxString &address, u_short port); // Get the socket state SocketState GetState() const { return m_sockstate; } // Get the socket handle int GetSocket() const { return m_sock; } // Test if the socket is readable bool IsReadable () const { return (m_sockstate == SOCKET_CONNECTED || m_sockstate == SOCKET_ACCEPTING); } // Test if the socket is writeable bool IsWritable () const { return (m_sockstate != SOCKET_CONNECTED || m_sockstate == SOCKET_WRITE_BLOCKED); } // Get the address of the socket wxString GetAddress() const; // Get the port number of the socket int GetPort() const; // Read the whole buffer of size length into buffer buffer from the socket int Read(char *buffer, int length); // Write the whole buffer of size length to the socket void Write(const char *buffer, int length); // Shutdown the socket void Shutdown(int how); // Close the socket void Close(); private: // Prevent copying and assignment of this class wxLuaSocket(const wxLuaSocket&); wxLuaSocket& operator=(const wxLuaSocket&); socket_type m_sock; sockaddr_in m_sockaddress; SocketState m_sockstate; }; // ---------------------------------------------------------------------------- // wxLuaSocketException // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaSocketException { public: enum SocketErrorCode { SOCKET_NOT_CLOSED, SOCKET_NOT_CONNECTED, SOCKET_NOT_LISTENING, SOCKET_INVALID_SOCKET, SOCKET_ADDRESS_NOT_RESOLVED, SOCKET_INCOMPATIBLE_TYPE, SOCKET_SET_BLOCKING_FAILED, SOCKET_ACCEPT_FAILED, SOCKET_CONNECT_FAILED, SOCKET_BIND_FAILED, SOCKET_LISTEN_FAILED, SOCKET_SEND_FAILED, SOCKET_RECEIVE_FAILED, SOCKET_CLOSE_FAILED }; // constructors wxLuaSocketException(SocketErrorCode code) : m_code(code) { #ifdef WIN32 m_errnum = ::WSAGetLastError(); switch(m_errnum) { case WSANOTINITIALISED: m_description = _("A successful WSAStartup must occur before using this function."); break; case WSAENETDOWN: m_description = _("The network subsystem or the associated service provider has failed."); break; case WSAEAFNOSUPPORT: m_description = _("The specified address family is not supported."); break; case WSAEINPROGRESS: m_description = _("A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function."); break; case WSAEMFILE: m_description = _("No more socket descriptors are available."); break; case WSAENOBUFS: m_description = _("No buffer space is available. The socket cannot be created."); break; case WSAEPROTONOSUPPORT: m_description = _("The specified protocol is not supported."); break; case WSAEPROTOTYPE: m_description = _("The specified protocol is the wrong type for this socket."); break; case WSAESOCKTNOSUPPORT: m_description = _("The specified socket type is not supported in this address family."); break; } #else m_errnum = errno; #endif if (m_description.IsEmpty()) m_description = _("Socket Error"); } wxLuaSocketException(const wxLuaSocketException &e) : m_code(e.m_code), m_errnum(e.m_errnum) { } SocketErrorCode GetCode() const { return m_code; } int errnum() const { return m_errnum; } const wxString& description() { return m_description; } private: wxLuaSocketException& operator=(const wxLuaSocketException& e); SocketErrorCode m_code; int m_errnum; wxString m_description; }; #endif // WX_LUA_SOCKET_H_ |
From: John L. <jr...@us...> - 2005-06-06 23:06:28
|
Update of /cvsroot/wxlua/wxLua/modules/wxluadebug/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/wxluadebug/src Added Files: debug.cpp splttree.cpp staktree.cpp Log Message: moved files to the modules directory structure --- NEW FILE: splttree.cpp --- ///////////////////////////////////////////////////////////////////////////// // Name: splittree.cpp // Purpose: Classes to achieve a remotely-scrolled tree in a splitter // window that can be scrolled by a scrolled window higher in the // hierarchy // Author: Julian Smart // Created: 8/7/2000 // Modified by: J. Winwood, to fix a few bugs and also add a second // splitter and scrolled window (three columns rather than two). // Copyright: (c) Julian Smart // (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "splttree.h" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #ifdef __WXMSW__ #include <windows.h> #include "wx/msw/winundef.h" #endif #include "wxlua/splttree.h" #include <math.h> static wxTreeItemId defaultTreeItemId; /* * wxRemotelyScrolledTreeCtrl */ #if USE_GENERIC_TREECTRL IMPLEMENT_CLASS(wxRemotelyScrolledTreeCtrl, wxGenericTreeCtrl) #else IMPLEMENT_CLASS(wxRemotelyScrolledTreeCtrl, wxTreeCtrl) #endif #if USE_GENERIC_TREECTRL BEGIN_EVENT_TABLE(wxRemotelyScrolledTreeCtrl, wxGenericTreeCtrl) #else BEGIN_EVENT_TABLE(wxRemotelyScrolledTreeCtrl, wxTreeCtrl) #endif EVT_SIZE(wxRemotelyScrolledTreeCtrl::OnSize) EVT_PAINT(wxRemotelyScrolledTreeCtrl::OnPaint) EVT_TREE_ITEM_EXPANDED(-1, wxRemotelyScrolledTreeCtrl::OnExpand) EVT_TREE_ITEM_COLLAPSED(-1, wxRemotelyScrolledTreeCtrl::OnExpand) EVT_SCROLLWIN(wxRemotelyScrolledTreeCtrl::OnScroll) EVT_TREE_SEL_CHANGED(-1, wxRemotelyScrolledTreeCtrl::OnSelChanged) END_EVENT_TABLE() wxRemotelyScrolledTreeCtrl::wxRemotelyScrolledTreeCtrl(wxWindow *parent, wxWindowID id, const wxPoint& pt, const wxSize& sz, long style) : wxTreeCtrl(parent, id, pt, sz, style & ~wxTR_ROW_LINES), m_lastTreeItemId(defaultTreeItemId) { m_firstCompanionWindow = NULL; m_secondCompanionWindow = NULL; // We draw the row lines ourself so they match what's done // by the companion window. That is why the flag is turned // off above, so wxGenericTreeCtrl doesn't draw them in a // different colour. m_drawRowLines = (style & wxTR_ROW_LINES) != 0; } wxRemotelyScrolledTreeCtrl::~wxRemotelyScrolledTreeCtrl() { } void wxRemotelyScrolledTreeCtrl::HideVScrollbar() { #if defined(__WXMSW__) #if USE_GENERIC_TREECTRL if (!IsKindOf(CLASSINFO(wxGenericTreeCtrl))) #endif { ::ShowScrollBar((HWND) GetHWND(), SB_VERT, FALSE); } #if USE_GENERIC_TREECTRL else { // Implicit in overriding SetScrollbars } #endif #endif } // Number of pixels per user unit (0 or -1 for no scrollbar) // Length of virtual canvas in user units // Length of page in user units void wxRemotelyScrolledTreeCtrl::SetScrollbars(int pixelsPerUnitX, int pixelsPerUnitY, int noUnitsX, int noUnitsY, int xPos, int yPos, bool noRefresh) { #if USE_GENERIC_TREECTRL || !defined(__WXMSW__) if (IsKindOf(CLASSINFO(wxGenericTreeCtrl))) { wxGenericTreeCtrl* win = (wxGenericTreeCtrl*) this; win->wxGenericTreeCtrl::SetScrollbars(pixelsPerUnitX, pixelsPerUnitY, noUnitsX, 0, xPos, 0, /* noRefresh */ TRUE); wxScrolledWindow* scrolledWindow = GetScrolledWindow(); if (scrolledWindow) { scrolledWindow->SetScrollbars(0, pixelsPerUnitY, 0, noUnitsY, 0, yPos, noRefresh); scrolledWindow->AdjustScrollbars(); // FIXME - this is for the broken wxWindow's wxScrolledWindow } } #else # ifdef UNREFERENCED_PARAMETER UNREFERENCED_PARAMETER(pixelsPerUnitX); UNREFERENCED_PARAMETER(pixelsPerUnitY); UNREFERENCED_PARAMETER(noUnitsX); UNREFERENCED_PARAMETER(noUnitsY); UNREFERENCED_PARAMETER(xPos); UNREFERENCED_PARAMETER(yPos); UNREFERENCED_PARAMETER(noRefresh); # endif #endif } // In case we're using the generic tree control. int wxRemotelyScrolledTreeCtrl::GetScrollPos(int orient) const { #if USE_GENERIC_TREECTRL || !defined(__WXMSW__) wxScrolledWindow* scrolledWindow = GetScrolledWindow(); if (IsKindOf(CLASSINFO(wxGenericTreeCtrl))) { wxGenericTreeCtrl* win = (wxGenericTreeCtrl*) this; if (orient == wxHORIZONTAL) return win->wxGenericTreeCtrl::GetScrollPos(orient); else return scrolledWindow->GetScrollPos(orient); } #else # ifdef UNREFERENCED_PARAMETER UNREFERENCED_PARAMETER(orient); # endif #endif return 0; } // In case we're using the generic tree control. // Get the view start void wxRemotelyScrolledTreeCtrl::GetViewStart(int *x, int *y) const { wxScrolledWindow* scrolledWindow = GetScrolledWindow(); #if USE_GENERIC_TREECTRL || !defined(__WXMSW__) if (IsKindOf(CLASSINFO(wxGenericTreeCtrl))) { wxGenericTreeCtrl* win = (wxGenericTreeCtrl*) this; int x1, y1, x2, y2; win->wxGenericTreeCtrl::GetViewStart(& x1, & y1); * x = x1; * y = y1; if (!scrolledWindow) return; scrolledWindow->GetViewStart(& x2, & y2); * y = y2; } else #endif { // x is wrong since the horizontal scrollbar is controlled by the // tree control, but we probably don't need it. scrolledWindow->GetViewStart(x, y); } } // In case we're using the generic tree control. void wxRemotelyScrolledTreeCtrl::PrepareDC(wxDC& dc) { #if USE_GENERIC_TREECTRL || !defined(__WXMSW__) if (IsKindOf(CLASSINFO(wxGenericTreeCtrl))) { wxScrolledWindow* scrolledWindow = GetScrolledWindow(); wxGenericTreeCtrl* win = (wxGenericTreeCtrl*) this; int startX, startY; GetViewStart(& startX, & startY); int xppu1, yppu1, xppu2, yppu2; win->wxGenericTreeCtrl::GetScrollPixelsPerUnit(& xppu1, & yppu1); scrolledWindow->GetScrollPixelsPerUnit(& xppu2, & yppu2); dc.SetDeviceOrigin( -startX * xppu1, -startY * yppu2 ); // dc.SetUserScale( win->GetScaleX(), win->GetScaleY() ); } #else # ifdef UNREFERENCED_PARAMETER UNREFERENCED_PARAMETER(dc); # endif #endif } // Scroll to the given line (in scroll units where each unit is // the height of an item) void wxRemotelyScrolledTreeCtrl::ScrollToLine(int WXUNUSED(posHoriz), int posVert) { #ifdef __WXMSW__ #if USE_GENERIC_TREECTRL if (!IsKindOf(CLASSINFO(wxGenericTreeCtrl))) #endif { UINT sbCode = SB_THUMBPOSITION; HWND vertScrollBar = 0; #if wxMINOR_VERSION < 5 MSWDefWindowProc((WXUINT) WM_VSCROLL, MAKELONG(sbCode, posVert), (WXHWND) vertScrollBar); #else MSWDefWindowProc((WXUINT) WM_VSCROLL, MAKELONG(sbCode, posVert), (WXLPARAM) vertScrollBar); #endif } #if USE_GENERIC_TREECTRL else #endif #endif #if USE_GENERIC_TREECTRL || !defined(__WXMSW__) { wxGenericTreeCtrl* win = (wxGenericTreeCtrl*) this; win->Refresh(); } #endif } void wxRemotelyScrolledTreeCtrl::OnSize(wxSizeEvent& event) { HideVScrollbar(); AdjustRemoteScrollbars(); if (m_firstCompanionWindow) m_firstCompanionWindow->Refresh(TRUE); if (m_secondCompanionWindow) m_secondCompanionWindow->Refresh(TRUE); event.Skip(); } void wxRemotelyScrolledTreeCtrl::OnExpand(wxTreeEvent& event) { AdjustRemoteScrollbars(); event.Skip(); // If we don't have this, we get some bits of lines still remaining if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_COLLAPSED) Refresh(); // Pass on the event if (m_secondCompanionWindow) m_secondCompanionWindow->GetEventHandler()->ProcessEvent(event); if (m_firstCompanionWindow) m_firstCompanionWindow->GetEventHandler()->ProcessEvent(event); } void wxRemotelyScrolledTreeCtrl::OnSelChanged(wxTreeEvent& event) { const wxTreeItemId &itemId = GetFirstVisibleItem(); if (m_lastTreeItemId != itemId) { AdjustRemoteScrollbars(); event.Skip(); Refresh(); // Pass on the event if (m_secondCompanionWindow) m_secondCompanionWindow->GetEventHandler()->ProcessEvent(event); if (m_firstCompanionWindow) m_firstCompanionWindow->GetEventHandler()->ProcessEvent(event); m_lastTreeItemId = itemId; } else event.Skip(); } void wxRemotelyScrolledTreeCtrl::OnPaint(wxPaintEvent& event) { wxPaintDC dc(this); wxTreeCtrl::OnPaint(event); if (! m_drawRowLines) return; // Reset the device origin since it may have been set dc.SetDeviceOrigin(0, 0); wxPen pen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DLIGHT), 1, wxSOLID); dc.SetPen(pen); dc.SetBrush(*wxTRANSPARENT_BRUSH); wxSize clientSize = GetClientSize(); wxRect itemRect; int cy = 0; wxTreeItemId h, lastH; for(h = GetFirstVisibleItem(); h && IsVisible(h); h = GetNextVisible(h)) { if (GetBoundingRect(h, itemRect)) { cy = itemRect.GetTop(); dc.DrawLine(0, cy, clientSize.x, cy); lastH = h; } } if (lastH.IsOk() && GetBoundingRect(lastH, itemRect)) { cy = itemRect.GetBottom(); dc.DrawLine(0, cy, clientSize.x, cy); } } // Adjust the containing wxScrolledWindow's scrollbars appropriately void wxRemotelyScrolledTreeCtrl::AdjustRemoteScrollbars() { #if USE_GENERIC_TREECTRL || !defined(__WXMSW__) if (IsKindOf(CLASSINFO(wxGenericTreeCtrl))) { // This is for the generic tree control. // It calls SetScrollbars which has been overridden // to adjust the parent scrolled window vertical // scrollbar. ((wxGenericTreeCtrl*) this)->AdjustMyScrollbars(); return; } else #endif { // This is for the wxMSW tree control wxScrolledWindow* scrolledWindow = GetScrolledWindow(); if (scrolledWindow) { wxRect itemRect; if (GetBoundingRect(GetFirstVisibleItem(), itemRect)) // newer method //if (GetBoundingRect(GetRootItem(), itemRect)) { // Actually, the real height seems to be 1 less than reported // (e.g. 16 instead of 16) int itemHeight = itemRect.GetHeight() - 1; int w, h; GetClientSize(&w, &h); wxRect rect(0, 0, 0, 0); CalcTreeSize(rect); double f = ((double) (rect.GetHeight()) / (double) itemHeight) ; int treeViewHeight = (int) ceil(f); int scrollPixelsPerLine = itemHeight; int scrollPos = - (itemRect.y / itemHeight); scrolledWindow->SetScrollbars(0, scrollPixelsPerLine, 0, treeViewHeight - 1, 0, scrollPos); // Ensure that when a scrollbar becomes hidden or visible, // the contained window sizes are right. // Problem: this is called too early (?) wxSizeEvent event(scrolledWindow->GetSize(), scrolledWindow->GetId()); scrolledWindow->GetEventHandler()->ProcessEvent(event); } } } } void wxRemotelyScrolledTreeCtrl::DeleteAllItems() { wxTreeCtrl::DeleteAllItems(); if (m_firstCompanionWindow) m_firstCompanionWindow->Refresh(TRUE); if (m_secondCompanionWindow) m_secondCompanionWindow->Refresh(TRUE); } // Calculate the area that contains both rectangles static wxRect CombineRectangles(const wxRect& rect1, const wxRect& rect2) { wxRect rect; int right1 = rect1.GetRight(); int bottom1 = rect1.GetBottom(); int right2 = rect2.GetRight(); int bottom2 = rect2.GetBottom(); wxPoint topLeft = wxPoint(wxMin(rect1.x, rect2.x), wxMin(rect1.y, rect2.y)); wxPoint bottomRight = wxPoint(wxMax(right1, right2), wxMax(bottom1, bottom2)); rect.x = topLeft.x; rect.y = topLeft.y; rect.SetRight(bottomRight.x); rect.SetBottom(bottomRight.y); return rect; } // Calculate the tree overall size so we can set the scrollbar // correctly void wxRemotelyScrolledTreeCtrl::CalcTreeSize(wxRect& rect) { CalcTreeSize(GetRootItem(), rect); } void wxRemotelyScrolledTreeCtrl::CalcTreeSize(const wxTreeItemId& id, wxRect& rect) { // More efficient implementation would be to find the last item (but how?) // Q: is the bounding rect relative to the top of the virtual tree workspace // or the top of the window? How would we convert? wxRect itemSize; if (GetBoundingRect(id, itemSize)) { rect = CombineRectangles(rect, itemSize); } wxTreeItemIdValue cookie; wxTreeItemId childId = GetFirstChild(id, cookie); while (childId != wxTreeItemId((long)0)) { CalcTreeSize(childId, rect); childId = GetNextChild(childId, cookie); } } // Find the scrolled window that contains this control wxScrolledWindow* wxRemotelyScrolledTreeCtrl::GetScrolledWindow() const { wxWindow* parent = wxWindow::GetParent(); while (parent) { if (parent->IsKindOf(CLASSINFO(wxScrolledWindow))) return (wxScrolledWindow*) parent; parent = parent->GetParent(); } return NULL; } void wxRemotelyScrolledTreeCtrl::OnScroll(wxScrollWinEvent& event) { int orient = event.GetOrientation(); if (orient == wxHORIZONTAL) { event.Skip(); return; } wxScrolledWindow* scrollWin = GetScrolledWindow(); if (!scrollWin) return; int x, y; scrollWin->GetViewStart(& x, & y); ScrollToLine(-1, y); // Pass on the event if (m_secondCompanionWindow) m_secondCompanionWindow->GetEventHandler()->ProcessEvent(event); if (m_firstCompanionWindow) m_firstCompanionWindow->GetEventHandler()->ProcessEvent(event); } /* * wxTreeCompanionWindow * * A window displaying values associated with tree control items. */ IMPLEMENT_CLASS(wxTreeCompanionWindow, wxWindow) BEGIN_EVENT_TABLE(wxTreeCompanionWindow, wxWindow) EVT_PAINT(wxTreeCompanionWindow::OnPaint) EVT_SCROLLWIN(wxTreeCompanionWindow::OnScroll) EVT_TREE_ITEM_EXPANDED(-1, wxTreeCompanionWindow::OnExpand) EVT_TREE_ITEM_COLLAPSED(-1, wxTreeCompanionWindow::OnExpand) EVT_TREE_SEL_CHANGED(-1, wxTreeCompanionWindow::OnSelChanged) END_EVENT_TABLE() wxTreeCompanionWindow::wxTreeCompanionWindow(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& sz, long style): wxWindow(parent, id, pos, sz, style) { m_treeControl = NULL; } wxTreeCompanionWindow::~wxTreeCompanionWindow() { } void wxTreeCompanionWindow::DrawItem(wxDC& dc, wxTreeItemId id, const wxRect& rect) { if (m_treeControl) { wxString text = m_treeControl->GetItemText(id); dc.SetTextForeground(*wxBLACK); dc.SetBackgroundMode(wxTRANSPARENT); int textW, textH; dc.GetTextExtent(text, &textW, &textH); int x = 5; int y = rect.GetY() + wxMax(0, (rect.GetHeight() - textH) / 2); dc.DrawText(text, x, y); } } void wxTreeCompanionWindow::OnPaint(wxPaintEvent& WXUNUSED(event)) { if (m_treeControl == NULL) return; wxMemoryDC tempDC; wxSize clientSize = GetClientSize(); wxBitmap tempBitmap(clientSize.x, clientSize.y); tempDC.SelectObject(tempBitmap); tempDC.Clear(); wxPen pen(wxSystemSettings::GetSystemColour(wxSYS_COLOUR_3DLIGHT), 1, wxSOLID); tempDC.SetPen(pen); tempDC.SetBrush(*wxTRANSPARENT_BRUSH); wxFont font(wxSystemSettings::GetSystemFont(wxSYS_DEFAULT_GUI_FONT)); tempDC.SetFont(font); wxRect itemRect; int cy = 0; wxTreeItemId h, lastH; for(h = m_treeControl->GetFirstVisibleItem(); h && m_treeControl->IsVisible(h); h = m_treeControl->GetNextVisible(h)) { if (m_treeControl->GetBoundingRect(h, itemRect)) { cy = itemRect.GetTop(); wxRect drawItemRect(0, cy, clientSize.x, itemRect.GetHeight()); lastH = h; // Draw the actual item DrawItem(tempDC, h, drawItemRect); tempDC.DrawLine(0, cy, clientSize.x, cy); } } if (lastH.IsOk() && m_treeControl->GetBoundingRect(lastH, itemRect)) { cy = itemRect.GetBottom(); tempDC.DrawLine(0, cy, clientSize.x, cy); } wxPaintDC dc(this); dc.Blit(0, 0, clientSize.x, clientSize.y, &tempDC, 0, 0); tempDC.SelectObject(wxNullBitmap); } void wxTreeCompanionWindow::OnScroll(wxScrollWinEvent& event) { int orient = event.GetOrientation(); if (orient == wxHORIZONTAL) { event.Skip(); return; } if (!m_treeControl) return; // TODO: scroll the window physically instead of just refreshing. Refresh(TRUE); } void wxTreeCompanionWindow::OnExpand(wxTreeEvent& WXUNUSED(event)) { // TODO: something more optimized than simply refresh the whole // window when the tree is expanded/collapsed. Tricky. Refresh(); } void wxTreeCompanionWindow::OnSelChanged(wxTreeEvent& WXUNUSED(event)) { Refresh(); } /* * wxThinSplitterWindow */ IMPLEMENT_CLASS(wxThinSplitterWindow, wxSplitterWindow) BEGIN_EVENT_TABLE(wxThinSplitterWindow, wxSplitterWindow) EVT_SIZE(wxThinSplitterWindow::OnSize) END_EVENT_TABLE() wxThinSplitterWindow::wxThinSplitterWindow(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& sz, long style): wxSplitterWindow(parent, id, pos, sz, style) { } void wxThinSplitterWindow::SizeWindows() { // The client size may have changed inbetween // the sizing of the first window and the sizing of // the second. So repeat SizeWindows. wxSplitterWindow::SizeWindows(); wxSplitterWindow::SizeWindows(); } // Tests for x, y over sash bool wxThinSplitterWindow::SashHitTest(int x, int y, int WXUNUSED(tolerance)) { return wxSplitterWindow::SashHitTest(x, y, 4); } void wxThinSplitterWindow::DrawSash(wxDC& dc) { if ( m_sashPosition == 0 || !m_windowTwo) return; if (GetWindowStyle() & wxSP_NOSASH) return; int w, h; GetClientSize(&w, &h); wxColour faceColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE)); wxPen facePen(faceColour, 1, wxSOLID); wxBrush faceBrush(faceColour, wxSOLID); if ( m_splitMode == wxSPLIT_VERTICAL ) { dc.SetPen(facePen); dc.SetBrush(faceBrush); int h1 = h-1; int y1 = 0; if ( (GetWindowStyleFlag() & wxSP_BORDER) != wxSP_BORDER && (GetWindowStyleFlag() & wxSP_3DBORDER) != wxSP_3DBORDER ) h1 += 1; // Not sure why this is necessary... if ( (GetWindowStyleFlag() & wxSP_3DBORDER) == wxSP_3DBORDER) { y1 = 2; h1 -= 3; } dc.DrawRectangle(m_sashPosition, y1, 3, h1); // 3 == m_sashSize now gone in wxWidgets >= 2.5 } else { dc.SetPen(facePen); dc.SetBrush(faceBrush); int w1 = w-1; int x1 = 0; if ( (GetWindowStyleFlag() & wxSP_BORDER) != wxSP_BORDER && (GetWindowStyleFlag() & wxSP_3DBORDER) != wxSP_3DBORDER ) w1 ++; if ( (GetWindowStyleFlag() & wxSP_3DBORDER) == wxSP_3DBORDER) { x1 = 2; w1 -= 3; } dc.DrawRectangle(x1, m_sashPosition, w1, 3); } dc.SetPen(wxNullPen); dc.SetBrush(wxNullBrush); } void wxThinSplitterWindow::OnSize(wxSizeEvent& event) { wxSplitterWindow::OnSize(event); } /* * wxSplitterScrolledWindow */ IMPLEMENT_CLASS(wxSplitterScrolledWindow, wxScrolledWindow) BEGIN_EVENT_TABLE(wxSplitterScrolledWindow, wxScrolledWindow) EVT_SCROLLWIN(wxSplitterScrolledWindow::OnScroll) EVT_SIZE(wxSplitterScrolledWindow::OnSize) END_EVENT_TABLE() wxSplitterScrolledWindow::wxSplitterScrolledWindow(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& sz, long style): wxScrolledWindow(parent, id, pos, sz, style) { } void wxSplitterScrolledWindow::OnSize(wxSizeEvent& WXUNUSED(event)) { wxSize sz = GetClientSize(); if (GetChildren().GetFirst()) { ((wxWindow*) GetChildren().GetFirst()->GetData())->SetSize(0, 0, sz.x, sz.y); } } void wxSplitterScrolledWindow::OnScroll(wxScrollWinEvent& event) { // Ensure that events being propagated back up the window hierarchy // don't cause an infinite loop static bool inOnScroll = FALSE; if (inOnScroll) { event.Skip(); return; } inOnScroll = TRUE; int orient = event.GetOrientation(); int nScrollInc = CalcScrollInc(event); if (nScrollInc == 0) { inOnScroll = FALSE; return; } if (orient == wxHORIZONTAL) { inOnScroll = FALSE; event.Skip(); return; } else { int newPos = m_yScrollPosition + nScrollInc; SetScrollPos(wxVERTICAL, newPos, TRUE ); } if (orient == wxHORIZONTAL) { m_xScrollPosition += nScrollInc; } else { m_yScrollPosition += nScrollInc; } // Find targets in splitter window and send the event to them wxWindowListNode* node = GetChildren().GetFirst(); while (node) { wxWindow* child = (wxWindow*) node->GetData(); if (child->IsKindOf(CLASSINFO(wxSplitterWindow))) { wxSplitterWindow* splitter = (wxSplitterWindow*) child; if (splitter->GetWindow1()) splitter->GetWindow1()->ProcessEvent(event); if (splitter->GetWindow2()) splitter->GetWindow2()->ProcessEvent(event); break; } node = node->GetNext(); } #ifdef __WXMAC__ m_targetWindow->MacUpdateImmediately() ; #endif inOnScroll = FALSE; } --- NEW FILE: staktree.cpp --- ///////////////////////////////////////////////////////////////////////////// // Name: StackTree.cpp // Purpose: Display the lua stack in a dialog. // Author: J. Winwood // Created: February 2002 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "staktree.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/imaglist.h" #include "wxlua/staktree.h" #include "wxlua/internal.h" #include "wxlua/wxlua.h" #include "wxlua/debugio.h" #include "wxlua/dserver.h" #include "wxlua/library.h" #if defined(__WXGTK__) || defined(__WXMAC__) || defined(__WXMOTIF__) #include "../wxLua.xpm" #endif #if !defined(__WXMSW__) || wxUSE_XPM_IN_MSW /* Closed folder */ static char * icon1_xpm[] = { /* width height ncolors chars_per_pixel */ "16 16 6 1", /* colors */ " s None c None", ". c #000000", "+ c #c0c0c0", "@ c #808080", "# c #ffff00", "$ c #ffffff", /* pixels */ " ", " @@@@@ ", " @#+#+#@ ", " @#+#+#+#@@@@@@ ", " @$$$$$$$$$$$$@.", " @$#+#+#+#+#+#@.", " @$+#+#+#+#+#+@.", " @$#+#+#+#+#+#@.", " @$+#+#+#+#+#+@.", " @$#+#+#+#+#+#@.", " @$+#+#+#+#+#+@.", " @$#+#+#+#+#+#@.", " @@@@@@@@@@@@@@.", " ..............", " ", " " }; /* File */ static char * icon2_xpm[] = { /* width height ncolors chars_per_pixel */ "16 16 3 1", /* colors */ " s None c None", ". c #000000", "+ c #ffffff", /* pixels */ " ", " ........ ", " .++++++.. ", " .+.+.++.+. ", " .++++++.... ", " .+.+.+++++. ", " .+++++++++. ", " .+.+.+.+.+. ", " .+++++++++. ", " .+.+.+.+.+. ", " .+++++++++. ", " .+.+.+.+.+. ", " .+++++++++. ", " ........... ", " ", " " }; #endif // ---------------------------------------------------------------------------- // wxLuaStackFrame // ---------------------------------------------------------------------------- wxLuaStackFrame::wxLuaStackFrame( wxWindow *parent, const wxString &title, const wxPoint &pos, const wxSize &size, wxLuaDebugServer *pServer) : wxDialog(parent, idSTACK_FRAME, title, pos, size, wxCAPTION | wxSYSTEM_MENU | wxDIALOG_MODAL | wxRESIZE_BORDER), m_luaInterface(NULL), m_pServer(pServer) { Construct(); } wxLuaStackFrame::wxLuaStackFrame( wxWindow *parent, const wxString &title, const wxPoint &pos, const wxSize &size, wxLuaInterface *luaInterface) : wxDialog(parent, idSTACK_FRAME, title, pos, size, wxCAPTION | wxSYSTEM_MENU | wxDIALOG_MODAL | wxRESIZE_BORDER), m_luaInterface(luaInterface), m_pServer(NULL) { Construct(); } wxLuaStackFrame::~wxLuaStackFrame() { if (m_pServer != NULL) m_pServer->CleanupDebugReferences(); if (m_pServer != NULL) wxGetLuaHandler().SetStackFrame(NULL); } void wxLuaStackFrame::Construct() { m_treeSplitter = NULL; m_valueSplitter = NULL; m_scrolledWindow = NULL; m_treeControl = NULL; m_firstValueWindow = NULL; m_secondValueWindow = NULL; if (m_pServer != NULL) wxGetLuaHandler().SetStackFrame(this); m_stackComboBox = new wxComboBox( this, idSTACK_COMBOBOX, wxEmptyString, wxPoint(0, 0), wxDefaultSize, 0, NULL, wxCB_DROPDOWN | wxCB_READONLY); m_scrolledWindow = new wxSplitterScrolledWindow(this, idSCROLLED_WINDOW, wxDefaultPosition, wxDefaultSize, wxNO_BORDER | wxCLIP_CHILDREN | wxVSCROLL); #if wxCHECK_VERSION(2, 3, 0) m_dismissButton = new wxButton(this, idDISMISS_BUTTON, _("Cancel"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); #else m_dismissButton = new wxButton(this, idDISMISS_BUTTON, _("Cancel"), wxDefaultPosition, wxDefaultSize); #endif m_dismissButton->SetDefault(); m_treeSplitter = new wxThinSplitterWindow(m_scrolledWindow, idSPLITTER_WINDOW, wxDefaultPosition, wxDefaultSize, wxSP_3DBORDER | wxCLIP_CHILDREN); m_treeSplitter->SetSashSize(2); /* Note the wxTR_ROW_LINES style: draws horizontal lines between items */ #if wxCHECK_VERSION(2, 3, 0) m_treeControl = new wxLuaStackTree(m_treeSplitter, idSTACKTREE_CTRL, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS | wxTR_NO_LINES | wxNO_BORDER | wxTR_ROW_LINES ); #else m_treeControl = new wxLuaStackTree(m_treeSplitter, idSTACKTREE_CTRL, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS | wxTR_NO_LINES | wxNO_BORDER); #endif m_valueSplitter = new wxThinSplitterWindow(m_treeSplitter, idVALUE_SPLITTER_WINDOW, wxDefaultPosition, wxDefaultSize, wxSP_NOBORDER | wxCLIP_CHILDREN); m_valueSplitter->SetSashSize(2); m_firstValueWindow = new wxLuaStackDataWindow(m_valueSplitter, idFIRST_VALUE_WINDOW, wxDefaultPosition, wxDefaultSize, wxNO_BORDER); m_secondValueWindow = new wxLuaStackDataWindow(m_valueSplitter, idSECOND_VALUE_WINDOW, wxDefaultPosition, wxDefaultSize, wxNO_BORDER, false); m_treeSplitter->SetSashPosition(25); m_treeSplitter->SetMinimumPaneSize(10); m_treeSplitter->SplitVertically(m_treeControl, m_valueSplitter); m_valueSplitter->SetSashPosition(125); m_valueSplitter->SetMinimumPaneSize(10); m_valueSplitter->SplitVertically(m_firstValueWindow, m_secondValueWindow); m_scrolledWindow->SetTargetWindow(m_treeControl); m_scrolledWindow->EnableScrolling(FALSE, FALSE); // Let the two controls know about each other m_firstValueWindow->SetTreeCtrl(m_treeControl); m_secondValueWindow->SetTreeCtrl(m_treeControl); m_treeControl->SetCompanionWindows(m_firstValueWindow, m_secondValueWindow); // set the frame icon #if wxCHECK_VERSION(2, 3, 0) SetIcon(wxICON(LUA)); #endif int nWidth, nHeight; GetClientSize(&nWidth, &nHeight); SizeWindow(nWidth, nHeight); if (m_pServer != NULL) m_pServer->EnumerateStack(); else { wxLuaDebugData *pSortedList = m_luaInterface->BuildStack(); if (pSortedList != NULL) { FillStackCombobox(pSortedList); delete pSortedList; } } } void wxLuaStackFrame::FillStackCombobox(const wxLuaDebugData *pSortedList) { size_t idx; m_stackComboBox->Clear(); for (idx = 0; idx < pSortedList->Count(); ++idx) { const wxLuaDebugDataItem *item = pSortedList->Item(idx); #if defined(__WXMAC__) // Mac is dying on the two parameter version...don't know how to fix. m_stackComboBox->Append(item->GetName()); #else m_stackComboBox->Append(item->GetName(), (void *) item->GetReference()); #endif } if (pSortedList->Count() > 0) { m_stackComboBox->SetSelection(0); SelectStack(0); } } BEGIN_EVENT_TABLE(wxLuaStackFrame, wxDialog) EVT_SIZE(wxLuaStackFrame::OnSizeWindow) EVT_COMBOBOX(idSTACK_COMBOBOX, wxLuaStackFrame::OnSelectStack) EVT_TREE_ITEM_EXPANDING(idSTACKTREE_CTRL, wxLuaStackFrame::OnItemExpanding) EVT_BUTTON(idDISMISS_BUTTON, wxLuaStackFrame::OnCloseDialog) END_EVENT_TABLE() void wxLuaStackFrame::OnSizeWindow(wxSizeEvent &event) { wxSize size = GetClientSize(); //event.GetSize(); event size no good in > 2.5.3 at least SizeWindow(size.x, size.y); event.Skip(); } void wxLuaStackFrame::SizeWindow(int nWidth, int nHeight) { int nComboWidth, nComboHeight, nButtonWidth, nButtonHeight; m_stackComboBox->GetSize(&nComboWidth, &nComboHeight); m_dismissButton->GetSize(&nButtonWidth, &nButtonHeight); nComboHeight += 2; // makes it look a little better m_stackComboBox->SetSize(0, 0, nWidth, -1); m_scrolledWindow->SetSize(0, nComboHeight, nWidth, nHeight - 15 - nComboHeight - nButtonHeight); m_dismissButton->SetSize((nWidth / 2) - (nButtonWidth / 2), nHeight - 5 - nButtonHeight, nButtonWidth, nButtonHeight); } void wxLuaStackFrame::OnSelectStack(wxCommandEvent &event) { SelectStack(event.GetSelection()); } void wxLuaStackFrame::SelectStack(int nCurrentSel) { m_nCurrentSel = nCurrentSel; int nEntry = (int) m_stackComboBox->GetClientData(nCurrentSel); if (m_pServer != NULL) { m_pServer->EnumerateStackEntry(nEntry); } else { wxLuaDebugData *pSortedList = m_luaInterface->BuildStackList(nEntry); if (pSortedList != NULL) { FillStackEntry(nEntry, pSortedList); delete pSortedList; } } } void wxLuaStackFrame::FillStackEntry(int WXUNUSED(nEntry), const wxLuaDebugData *pSortedList) { m_treeControl->DeleteAllItems(); wxTreeItemId rootItem = m_treeControl->AddRoot(_("Locals"), -1, -1); m_treeControl->AdjustRemoteScrollbars(); size_t idx; for (idx = 0; idx < pSortedList->Count(); ++idx) { const wxLuaDebugDataItem *item = pSortedList->Item(idx); int nOffset = 1; if (item->GetReference() != LUA_NOREF) nOffset = 0; wxTreeItemId treeNode = m_treeControl->AppendItem(rootItem, item->GetName(), nOffset, nOffset, new wxLuaDebugDataItem(*item)); if (item->GetReference() != LUA_NOREF) m_treeControl->SetItemHasChildren(treeNode); } // If at global scope, process globals if (m_nCurrentSel == m_stackComboBox->GetCount() - 1) { if (m_pServer != NULL) m_pServer->EnumerateTable(-1, -1, rootItem); else { wxLuaDebugData *pSortedList = m_luaInterface->GetGlobalData(); const wxLuaDebugDataItem *item = pSortedList->Item(0); wxTreeItemId treeNode = m_treeControl->AppendItem( rootItem, item->GetName(), 0, 0, new wxLuaDebugDataItem(*item)); if (item->GetReference() != LUA_NOREF) m_treeControl->SetItemHasChildren(treeNode); GetDerivedAndTrackedItems(m_treeControl, rootItem); delete pSortedList; } } m_treeControl->Expand(rootItem); } void wxLuaStackFrame::GetDerivedAndTrackedItems(wxRemotelyScrolledTreeCtrl *treeControl, wxTreeItemId rootItem) { GET_LUASTATEVARS_RET(m_luaInterface->GetLuaState()) int derivedCount = 0, trackedCount = 0, appHandlerCount = 0, windowCount = 0; if (stateVars->m_pDerivedList) derivedCount = stateVars->m_pDerivedList->GetCount(); if (stateVars->m_pTrackedList) trackedCount = stateVars->m_pTrackedList->GetCount(); if (stateVars->m_pAppHandlerList) appHandlerCount = stateVars->m_pAppHandlerList->GetCount(); if (stateVars->m_pWindowList) windowCount = stateVars->m_pWindowList->GetCount(); treeControl->AppendItem (rootItem, wxT("Derived List"), 1, 1, new wxLuaDebugDataItem(_("Derived List"), wxT("wxLuaData"), wxT(""), wxString::Format(wxT("%d"), derivedCount), LUA_NOREF, 0)); treeControl->AppendItem (rootItem, wxT("Tracked List"), 1, 1, new wxLuaDebugDataItem(_("Tracked List"), wxT("wxLuaData"), wxT(""), wxString::Format(wxT("%d"), trackedCount), LUA_NOREF, 0)); treeControl->AppendItem (rootItem, wxT("AppHandler List"), 1, 1, new wxLuaDebugDataItem(_("AppHandler List"), wxT("wxLuaData"), wxT(""), wxString::Format(wxT("%d"), appHandlerCount), LUA_NOREF, 0)); treeControl->AppendItem (rootItem, wxT("wxWindow List"), 1, 1, new wxLuaDebugDataItem(_("wxWindow List"), wxT("wxLuaData"), wxT(""), wxString::Format(wxT("%d"), windowCount), LUA_NOREF, 0)); } void wxLuaStackFrame::OnItemExpanding(wxTreeEvent &event) { ItemExpanding(event.GetItem()); } void wxLuaStackFrame::ItemExpanding(const wxTreeItemId &itemNode) { if (itemNode) { wxLuaDebugDataItem *pDebugData = (wxLuaDebugDataItem *)m_treeControl->GetItemData(itemNode); if (pDebugData != NULL) { int nRef = pDebugData->GetReference(); if (nRef != LUA_NOREF) { int nIndex = pDebugData->GetIndex() + 1; if (!pDebugData->IsExpanded()) { pDebugData->SetExpanded(true); if (m_pServer != NULL) { m_pServer->EnumerateTable(nRef, nIndex, itemNode); } else { // insert items wxLuaDebugData *pSortedList = m_luaInterface->BuildTableList(nRef, nIndex); if (pSortedList != NULL) { FillTableEntry(itemNode, pSortedList); delete pSortedList; } } } } } } } void wxLuaStackFrame::FillTableEntry(wxTreeItemId itemNode, const wxLuaDebugData *pSortedList) { if (pSortedList->Count() == 0) m_treeControl->SetItemHasChildren(itemNode, false); else { size_t count; for (count = 0; count < pSortedList->Count(); ++count) { const wxLuaDebugDataItem *item = pSortedList->Item(count); int nOffset = 1; if (item->GetReference() != LUA_NOREF) nOffset = 0; wxTreeItemId treeNode = m_treeControl->AppendItem(itemNode, item->GetName(), nOffset, nOffset, new wxLuaDebugDataItem(*item)); if (item->GetReference() != LUA_NOREF) m_treeControl->SetItemHasChildren(treeNode); } } m_treeControl->Expand(itemNode); } void wxLuaStackFrame::OnCloseDialog(wxCommandEvent & WXUNUSED(event)) { EndModal(0); } // ---------------------------------------------------------------------------- // wxLuaStackTree // ---------------------------------------------------------------------------- wxLuaStackTree::wxLuaStackTree( wxWindow *parent, wxWindowID id, const wxPoint &pt, const wxSize &sz, long style) : wxRemotelyScrolledTreeCtrl(parent, id, pt, sz, style) { m_imageList = new wxImageList(16, 16, TRUE); #if !defined(__WXMSW__) // || wxUSE_XPM_IN_MSW m_imageList->Add(wxIcon(icon1_xpm)); m_imageList->Add(wxIcon(icon2_xpm)); #elif defined(__WXMSW__) m_imageList->Add(wxIcon(wxT("wxICON_SMALL_CLOSED_FOLDER"), wxBITMAP_TYPE_ICO_RESOURCE)); m_imageList->Add(wxIcon(wxT("wxICON_SMALL_FILE"), wxBITMAP_TYPE_ICO_RESOURCE)); #else #error "Sorry, we don't have icons available for this platforms." #endif SetImageList(m_imageList); } IMPLEMENT_CLASS(wxLuaStackTree, wxRemotelyScrolledTreeCtrl) BEGIN_EVENT_TABLE(wxLuaStackTree, wxRemotelyScrolledTreeCtrl) END_EVENT_TABLE() wxLuaStackTree::~wxLuaStackTree() { SetImageList(NULL); delete m_imageList; } // ---------------------------------------------------------------------------- // wxLuaStackDataWindow // ---------------------------------------------------------------------------- BEGIN_EVENT_TABLE(wxLuaStackDataWindow, wxTreeCompanionWindow) END_EVENT_TABLE() wxLuaStackDataWindow::wxLuaStackDataWindow(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &sz, long style, bool fFirst): wxTreeCompanionWindow(parent, id, pos, sz, style), m_fFirst(fFirst) { SetBackgroundColour(*wxWHITE); } void wxLuaStackDataWindow::DrawItem(wxDC &dc, wxTreeItemId id, const wxRect &rect) { if (m_treeControl) { wxLuaDebugDataItem *itemData = (wxLuaDebugDataItem *) m_treeControl->GetItemData(id); dc.SetTextForeground(*wxBLACK); dc.SetBackgroundMode(wxTRANSPARENT); int textWidth, textHeight = 0; if (itemData != NULL) { if (m_fFirst) dc.GetTextExtent(itemData->GetType(), &textWidth, &textHeight); else dc.GetTextExtent(itemData->GetValue(), &textWidth, &textHeight); } int x = 5; int y = rect.GetY() + wxMax(0, (rect.GetHeight() - textHeight) / 2); if (itemData != NULL) { if (m_fFirst) dc.DrawText(itemData->GetType(), x, y); else dc.DrawText(itemData->GetValue(), x, y); } } } --- NEW FILE: debug.cpp --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaDebug.cpp // Purpose: Debugging I/O functions for wxLua // Author: J. Winwood // Created: May 2002 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// // Ray Gilbert #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "debug.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wxlua/debug.h" #include "wxlua/internal.h" DEFINE_EVENT_TYPE(wxEVT_DEBUG_CLIENT_CONNECTED) DEFINE_EVENT_TYPE(wxEVT_DEBUG_BREAK) DEFINE_EVENT_TYPE(wxEVT_DEBUG_PRINT) DEFINE_EVENT_TYPE(wxEVT_DEBUG_ERROR) DEFINE_EVENT_TYPE(wxEVT_DEBUG_EXIT) DEFINE_EVENT_TYPE(wxEVT_DEBUG_STACK_ENUM) DEFINE_EVENT_TYPE(wxEVT_DEBUG_STACK_ENTRY_ENUM) DEFINE_EVENT_TYPE(wxEVT_DEBUG_TABLE_ENUM) DEFINE_EVENT_TYPE(wxEVT_DEBUG_EVALUATE_EXPR) DEFINE_EVENT_TYPE(wxEVT_DEBUG_STARTDEBUGGER) DEFINE_EVENT_TYPE(wxEVT_DEBUG_STOPDEBUGGER) DEFINE_EVENT_TYPE(wxEVT_DEBUG_BREAKPOINT_ADDED) DEFINE_EVENT_TYPE(wxEVT_DEBUG_BREAKPOINT_REMOVED) // ---------------------------------------------------------------------------- // wxLuaBuffer // ---------------------------------------------------------------------------- IMPLEMENT_CLASS(wxLuaBuffer, wxObject) wxLuaBuffer::wxLuaBuffer(const wxString &fileName, const wxString &buffer) : m_fileName(fileName), m_buffer(buffer) { } // ---------------------------------------------------------------------------- // wxLuaBuffer // ---------------------------------------------------------------------------- IMPLEMENT_CLASS(wxLuaDebuggerBase, wxEvtHandler) // ---------------------------------------------------------------------------- // wxLuaDebugEvent // ---------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxLuaDebugEvent, wxEvent) wxLuaDebugEvent::wxLuaDebugEvent() { m_fHasMessage = false; m_pDebugData = NULL; m_nReference = -1; m_fEnabledFlag = false; } wxLuaDebugEvent::wxLuaDebugEvent(int eventType) { SetEventType(eventType); m_fHasMessage = false; m_pDebugData = NULL; m_nReference = -1; m_fEnabledFlag = false; } wxLuaDebugEvent::wxLuaDebugEvent(int eventType, int lineNumber, const wxString &file, bool enabledFlag) { SetEventType(eventType); m_lineNumber = lineNumber; m_fileName = file; m_fHasMessage = false; m_nReference = -1; m_pDebugData = NULL; m_fEnabledFlag = enabledFlag; } wxLuaDebugEvent::~wxLuaDebugEvent() { if (m_pDebugData != NULL) delete m_pDebugData; } void wxLuaDebugEvent::SetMessage(const wxString &pMessage) { m_strMessage = pMessage; m_fHasMessage = true; } void wxLuaDebugEvent::SetDebugData(int nReference, wxLuaDebugData *pData) { m_nReference = nReference; m_pDebugData = pData; } int wxLuaDebugEvent::GetLineNumber() const { return m_lineNumber; } wxString wxLuaDebugEvent::GetFileName() const { return m_fileName; } wxString wxLuaDebugEvent::GetMessage() const { return m_strMessage; } bool wxLuaDebugEvent::GetEnabledFlag() const { return m_fEnabledFlag; } const wxLuaDebugData *wxLuaDebugEvent::GetDebugData() const { return m_pDebugData; } int wxLuaDebugEvent::GetReference() const { return m_nReference; } wxEvent *wxLuaDebugEvent::Clone() const { wxLuaDebugEvent *pEvent = new wxLuaDebugEvent(GetEventType(), m_lineNumber, m_fileName); if (pEvent != NULL) { if (m_fHasMessage) pEvent->SetMessage(m_strMessage); if (m_pDebugData != NULL) pEvent->SetDebugData(m_nReference, m_pDebugData->Clone()); else pEvent->SetDebugData(m_nReference); } return pEvent; } // ---------------------------------------------------------------------------- // wxLuaDebugDataItem // ---------------------------------------------------------------------------- wxLuaDebugDataItem::wxLuaDebugDataItem(const wxString &itemName, const wxString &itemType, const wxString &itemValue, const wxString &itemSource, int nReference, int nIndex, bool fExpanded) { m_itemName = itemName; m_itemType = itemType; m_itemValue = itemValue; m_itemSource = itemSource; m_nReference = nReference; m_nIndex = nIndex; m_fExpanded = fExpanded; } wxLuaDebugDataItem::wxLuaDebugDataItem(const wxLuaDebugDataItem &treeItem) { m_itemName = treeItem.m_itemName; m_itemType = treeItem.m_itemType; m_itemValue = treeItem.m_itemValue; m_itemSource = treeItem.m_itemSource; m_nReference = treeItem.m_nReference; m_nIndex = treeItem.m_nIndex; m_fExpanded = treeItem.m_fExpanded; } // ---------------------------------------------------------------------------- // wxLuaDebugData - Debug Info sent via socket to debugger client // ---------------------------------------------------------------------------- wxLuaDebugData::wxLuaDebugData() : wxLuaDebugDataItemArray(SortFunction) { } wxLuaDebugData::~wxLuaDebugData() { size_t idx; for (idx = 0; idx < Count(); ++idx) { const wxLuaDebugDataItem *pData = Item(idx); delete pData; } } wxLuaDebugData *wxLuaDebugData::Clone() { wxLuaDebugData *pCloneData = new wxLuaDebugData; if (pCloneData != NULL) { size_t idx; for (idx = 0; idx < Count(); ++idx) { const wxLuaDebugDataItem *pOldData = Item(idx); if (pOldData != NULL) pCloneData->Add(new wxLuaDebugDataItem(*pOldData)); } } return pCloneData; } int wxLuaDebugData::SortFunction(wxLuaDebugDataItem *elem1, wxLuaDebugDataItem *elem2 ) { return wxStrcmp(elem1->GetName(), elem2->GetName()); } // ---------------------------------------------------------------------------- // wxLuaInterface (local) // ---------------------------------------------------------------------------- wxLuaInterface::wxLuaInterface(lua_State *luaState) : m_luaState(luaState) { } wxLuaInterface::~wxLuaInterface() { size_t idx, idxMax = m_references.GetCount(); for (idx = 0; idx < idxMax; ++idx) { int iItem = m_references.Item(idx); tremove(m_luaState, iItem); } } int wxLuaInterface::GetStack(int nIndex, lua_Debug *luaDebug) { return lua_getstack(m_luaState, nIndex, luaDebug); } bool wxLuaInterface::GetInfo(const wxString &what, lua_Debug *luaDebug) { return (lua_getinfo(m_luaState, wx2lua(what), luaDebug) != 0); } wxString wxLuaInterface::GetLocal(lua_Debug *luaDebug, int index) { return lua2wx(lua_getlocal(m_luaState, luaDebug, index)); } void wxLuaInterface::GetGlobals() { lua_pushvalue(m_luaState, LUA_GLOBALSINDEX); } int wxLuaInterface::GetTop() { return lua_gettop(m_luaState); } int wxLuaInterface::Type(int index) { return lua_type(m_luaState, index); } double wxLuaInterface::ToNumber(int index) { return lua_tonumber(m_luaState, index); } int wxLuaInterface::ToBoolean(int index) { return lua_toboolean(m_luaState, index); } wxString wxLuaInterface::ToString(int index) { return lua2wx(lua_tostring(m_luaState, index)); } const void *wxLuaInterface::ToPointer(int index) { return lua_topointer(m_luaState, index); } bool wxLuaInterface::IsCFunction(int index) { return lua_iscfunction(m_luaState, index) != 0; } const void *wxLuaInterface::ToCFunction(int index) { return (const void *) lua_tocfunction(m_luaState, index); } const void *wxLuaInterface::ToUserData(int index) { return lua_touserdata(m_luaState, index); } int wxLuaInterface::GetTag(int index) { return ttag(m_luaState, index); } int wxLuaInterface::GetN(int index) { return luaL_getn(m_luaState, index); } int wxLuaInterface::Ref() { int nReference = tinsert(m_luaState, -1); m_references.Add(nReference); return nReference; } int wxLuaInterface::GetRef(int ref) { return tget(m_luaState, ref); } void wxLuaInterface::Pop(int count) { lua_pop(m_luaState, count); } void wxLuaInterface::PushNil() { lua_pushnil(m_luaState); } void wxLuaInterface::PushValue(int index) { lua_pushvalue(m_luaState, index); } int wxLuaInterface::Next(int index) { return lua_next(m_luaState, index); } wxLuaDebugData *wxLuaInterface::BuildStack() { wxLuaDebugData *pSortedList = new wxLuaDebugData(); int nIndex = 0; lua_Debug luaDebug; bool fFirst = true; while (GetStack(nIndex, &luaDebug) != 0) { if (GetInfo(wxT("Sln"), &luaDebug)) { wxString itemName; wxString source = lua2wx(luaDebug.source); // skip stack frames that do not have line number int currentLine = luaDebug.currentline; if (!fFirst || (currentLine != -1)) { if (currentLine == -1) currentLine = 0; if (luaDebug.name != NULL) itemName.Printf(_("function %s line %u"), luaDebug.name, currentLine); else itemName.Printf(_("line %u"), currentLine); wxLuaDebugDataItem *item = new wxLuaDebugDataItem(itemName, wxT(""), wxT(""), source, nIndex, 0); pSortedList->Add(item); fFirst = false; } } ++nIndex; } return pSortedList; } wxLuaDebugData *wxLuaInterface::BuildStackList(int nEntry) { wxLuaDebugData *pSortedList = new wxLuaDebugData(); if (pSortedList != NULL) { lua_Debug luaDebug; if (GetStack(nEntry, &luaDebug) != 0) { int idx = 1; wxString name = GetLocal(&luaDebug, idx); while (!name.IsEmpty()) { bool fIsTable = false; wxString type; wxString value; wxString source = lua2wx(luaDebug.source); switch (Type(-1)) { case LUA_TNIL: type = wxT("Nil"); value = wxT("nil"); break; case LUA_TBOOLEAN: type = wxT("Boolean"); value = MakeBoolean(ToBoolean(-1)); break; case LUA_TNUMBER: type = wxT("Number"); value = MakeNumber(ToNumber(-1)); break; case LUA_TSTRING: type = wxT("String"); value = ToString(-1); break; case LUA_TTABLE: type = wxT("Table"); value = GetTableInfo(-1); fIsTable = true; break; case LUA_TFUNCTION: if (IsCFunction(-1)) { type = wxT("C Function"); value.Printf(wxT("%p"), ToCFunction(-1)); } else { type = wxT("Lua Function"); value.Printf(wxT("%p"), ToPointer(-1)); } break; case LUA_TUSERDATA: type = wxT("User Data"); value = GetUserDataInfo(-1); break; case LUA_TLIGHTUSERDATA: type = wxT("Light User Data"); value = GetUserDataInfo(-1, false); break; case LUA_TTHREAD: type = wxT("Thread"); value.Printf(wxT("%p"), ToPointer(-1)); break; } int nRef = LUA_NOREF; if (fIsTable) { nRef = Ref(); } else Pop(1); wxLuaDebugDataItem *item = new wxLuaDebugDataItem(name, type, value, source, nRef, 0); pSortedList->Add(item); name = GetLocal(&luaDebug, ++idx); } } } return pSortedList; } wxLuaDebugData *wxLuaInterface::BuildTableList(int nRef, int nIndex) { wxLuaDebugData *pSortedList = new wxLuaDebugData(); if (pSortedList != NULL && GetRef(nRef) != 0) { int nTop = GetTop(); // start iterating PushNil(); while (Next(nTop) != 0) { bool fIsTable = false; wxString type; wxString value; wxString name; wxString source; // get the index switch (Type(-2)) { case LUA_TNIL: name = wxT("Nil"); break; case LUA_TBOOLEAN: name = MakeBoolean(ToBoolean(-2)); break; case LUA_TNUMBER: name = MakeNumber(ToNumber(-2)); break; case LUA_TSTRING: name = ToString(-2); break; case LUA_TTABLE: name = GetTableInfo(-2); break; case LUA_TFUNCTION: if (IsCFunction(-2)) name.Printf(wxT("%p"), ToCFunction(-2)); else name.Printf(wxT("%p"), ToPointer(-2)); break; case LUA_TUSERDATA: name = GetUserDataInfo(-2); break; case LUA_TLIGHTUSERDATA: name = GetUserDataInfo(-2, false); break; } // get the value switch (Type(-1)) { case LUA_TNIL: type = wxT("Nil"); value = wxT("nil"); break; case LUA_TBOOLEAN: value = MakeBoolean(ToBoolean(-1)); type = wxT("Boolean"); break; case LUA_TNUMBER: value = MakeNumber(ToNumber(-1)); type = wxT("Number"); break; case LUA_TSTRING: type = wxT("String"); value = ToString(-1); break; case LUA_TTABLE: type = wxT("Table"); value = GetTableInfo(-1); fIsTable = true; break; case LUA_TFUNCTION: if (IsCFunction(-1)) { type = wxT("C Function"); value.Printf(wxT("%p"), ToCFunction(-1)); } else { type = wxT("Lua Function"); value.Printf(wxT("%p"), ToPointer(-1)); } break; case LUA_TUSERDATA: type = wxT("User Data"); value = GetUserDataInfo(-1); break; case LUA_TLIGHTUSERDATA: type = wxT("Light User Data"); value = GetUserDataInfo(-1, false); break; case LUA_TTHREAD: type = wxT("Thread"); value.Printf(wxT("%p"), ToPointer(-1)); break; } int nRef = LUA_NOREF; if (fIsTable) nRef = Ref(); else Pop(1); wxLuaDebugDataItem *item = new wxLuaDebugDataItem(name, type, value, source, nRef, nIndex); pSortedList->Add(item); } // remove reference Pop(1); } return pSortedList; } wxString wxLuaInterface::GetTableInfo(int index) { wxString tableInfo; int nItems = GetN(index); const void *pItem = ToPointer(index); if (nItems == 0) tableInfo.Printf(wxT("%p"), pItem); else tableInfo.Printf(wxT("%p approx %u items)"), pItem, nItems); return tableInfo; } wxString wxLuaInterface::GetUserDataInfo(int index, bool full) { wxString userdatainfo; if (full) { wxString pTagName; int nTag = GetTag(index); if (nTag != TLUA_NOTAG) pTagName = lua2wx(... [truncated message content] |
Update of /cvsroot/wxlua/wxLua/modules/lua/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/test Added Files: README bisect.lua cf.lua compat.lua echo.lua env.lua factorial.lua fib.lua fibfor.lua globals.lua hello.lua life.lua luac.lua printf.lua readonly.lua sieve.lua sort.lua table.lua trace-calls.lua trace-globals.lua undefined.lua xd.lua Log Message: moved files to the modules directory structure --- NEW FILE: trace-calls.lua --- -- trace calls -- example: lua -ltrace-calls.lua bisect.lua local level=0 function hook(event) local t=debug.getinfo(3) io.write(level," >>> ",string.rep(" ",level)) if t~=nil and t.currentline>=0 then io.write(t.short_src,":",t.currentline," ") end t=debug.getinfo(2) if event=="call" then level=level+1 else level=level-1 if level<0 then level=0 end end if t.what=="main" then if event=="call" then io.write("begin ",t.short_src) else io.write("end ",t.short_src) end elseif t.what=="Lua" then -- table.foreach(t,print) io.write(event," ",t.name or "(Lua)"," <",t.linedefined,":",t.short_src,">") else io.write(event," ",t.name or "(C)"," [",t.what,"] ") end io.write("\n") end debug.sethook(hook,"cr") level=0 --- NEW FILE: hello.lua --- -- the first program in every language io.write("Hello world, from ",_VERSION,"!\n") --- NEW FILE: sieve.lua --- -- the sieve of of Eratosthenes programmed with coroutines -- typical usage: lua -e N=1000 sieve.lua | column -- generate all the numbers from 2 to n function gen (n) return coroutine.wrap(function () for i=2,n do coroutine.yield(i) end end) end -- filter the numbers generated by `g', removing multiples of `p' function filter (p, g) return coroutine.wrap(function () while 1 do local n = g() if n == nil then return end if math.mod(n, p) ~= 0 then coroutine.yield(n) end end end) end N=N or 1000 -- from command line x = gen(N) -- generate primes up to N while 1 do local n = x() -- pick a number until done if n == nil then break end print(n) -- must be a prime number x = filter(n, x) -- now remove its multiples end --- NEW FILE: echo.lua --- -- echo command line arguments for i=0,table.getn(arg) do print(i,arg[i]) end --- NEW FILE: xd.lua --- -- hex dump -- usage: lua xd.lua < file local offset=0 while 1 do local s=io.read(16) if s==nil then return end io.write(string.format("%08X ",offset)) string.gsub(s,"(.)",function (c) io.write(string.format("%02X ",string.byte(c))) end) io.write(string.rep(" ",3*(16-string.len(s)))) io.write(" ",string.gsub(s,"%c","."),"\n") offset=offset+16 end --- NEW FILE: trace-globals.lua --- -- trace assigments to global variables do -- a tostring that quotes strings. note the use of the original tostring. local _tostring=tostring local tostring=function(a) if type(a)=="string" then return string.format("%q",a) else return _tostring(a) end end local log=function (name,old,new) local t=debug.getinfo(3,"Sl") local line=t.currentline io.write(t.short_src) if line>=0 then io.write(":",line) end io.write(": ",name," is now ",tostring(new)," (was ",tostring(old),")","\n") end local g={} local set=function (t,name,value) log(name,g[name],value) g[name]=value end setmetatable(getfenv(),{__index=g,__newindex=set}) end -- an example a=1 b=2 a=10 b=20 b=nil b=200 print(a,b,c) --- NEW FILE: globals.lua --- -- reads luac listings and reports global variable usage -- lines where a global is written to are marked with "*" -- typical usage: luac -p -l file.lua | lua globals.lua | sort | lua table.lua while 1 do local s=io.read() if s==nil then break end local ok,_,l,op,g=string.find(s,"%[%-?(%d*)%]%s*([GS])ETGLOBAL.-;%s+(.*)$") if ok then if op=="S" then op="*" else op="" end io.write(g,"\t",l,op,"\n") end end --- NEW FILE: life.lua --- -- life.lua -- original by Dave Bollinger <DBo...@co...> posted to lua-l -- modified to use ANSI terminal escape sequences -- modified to use for instead of while local write=io.write ALIVE="¥" DEAD="þ" ALIVE="O" DEAD="-" function delay() -- NOTE: SYSTEM-DEPENDENT, adjust as necessary for i=1,10000 do end -- local i=os.clock()+1 while(os.clock()<i) do end end function ARRAY2D(w,h) local t = {w=w,h=h} for y=1,h do t[y] = {} for x=1,w do t[y][x]=0 end end return t end _CELLS = {} -- give birth to a "shape" within the cell array function _CELLS:spawn(shape,left,top) for y=0,shape.h-1 do for x=0,shape.w-1 do self[top+y][left+x] = shape[y*shape.w+x+1] end end end -- run the CA and produce the next generation function _CELLS:evolve(next) local ym1,y,yp1,yi=self.h-1,self.h,1,self.h while yi > 0 do local xm1,x,xp1,xi=self.w-1,self.w,1,self.w while xi > 0 do local sum = self[ym1][xm1] + self[ym1][x] + self[ym1][xp1] + self[y][xm1] + self[y][xp1] + self[yp1][xm1] + self[yp1][x] + self[yp1][xp1] next[y][x] = ((sum==2) and self[y][x]) or ((sum==3) and 1) or 0 xm1,x,xp1,xi = x,xp1,xp1+1,xi-1 end ym1,y,yp1,yi = y,yp1,yp1+1,yi-1 end end -- output the array to screen function _CELLS:draw() local out="" -- accumulate to reduce flicker for y=1,self.h do for x=1,self.w do out=out..(((self[y][x]>0) and ALIVE) or DEAD) end out=out.."\n" end write(out) end -- constructor function CELLS(w,h) local c = ARRAY2D(w,h) c.spawn = _CELLS.spawn c.evolve = _CELLS.evolve c.draw = _CELLS.draw return c end -- -- shapes suitable for use with spawn() above -- HEART = { 1,0,1,1,0,1,1,1,1; w=3,h=3 } GLIDER = { 0,0,1,1,0,1,0,1,1; w=3,h=3 } EXPLODE = { 0,1,0,1,1,1,1,0,1,0,1,0; w=3,h=4 } FISH = { 0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,1,0,0,1,0; w=5,h=4 } BUTTERFLY = { 1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,1; w=5,h=5 } -- the main routine function LIFE(w,h) -- create two arrays local thisgen = CELLS(w,h) local nextgen = CELLS(w,h) -- create some life -- about 1000 generations of fun, then a glider steady-state thisgen:spawn(GLIDER,5,4) thisgen:spawn(EXPLODE,25,10) thisgen:spawn(FISH,4,12) -- run until break local gen=1 write("\027[2J") -- ANSI clear screen while 1 do thisgen:evolve(nextgen) thisgen,nextgen = nextgen,thisgen write("\027[H") -- ANSI home cursor thisgen:draw() write("Life - generation ",gen,"\n") gen=gen+1 if gen>2000 then break end --delay() -- no delay end end LIFE(40,20) --- NEW FILE: table.lua --- -- make table, grouping all data for the same item -- input is 2 columns (item, data) local A while 1 do local l=io.read() if l==nil then break end local _,_,a,b=string.find(l,'"?([_%w]+)"?%s*(.*)$') if a~=A then A=a io.write("\n",a,":") end io.write(" ",b) end io.write("\n") --- NEW FILE: undefined.lua --- -- catch "undefined" global variables local f=function (t,i) error("undefined global variable `"..i.."'",2) end setmetatable(getfenv(),{__index=f}) -- an example a=1 c=3 print(a,b,c) -- `b' is undefined --- NEW FILE: printf.lua --- -- an implementation of printf function printf(...) io.write(string.format(unpack(arg))) end printf("Hello %s from %s on %s\n",os.getenv"USER" or "there",_VERSION,os.date()) --- NEW FILE: sort.lua --- -- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x) --- NEW FILE: cf.lua --- -- temperature conversion table (celsius to farenheit) for c0=-20,50-1,10 do io.write("C ") for c=c0,c0+10-1 do io.write(string.format("%3.0f ",c)) end io.write("\n") io.write("F ") for c=c0,c0+10-1 do f=(9/5)*c+32 io.write(string.format("%3.0f ",f)) end io.write("\n\n") end --- NEW FILE: fibfor.lua --- -- example of for with generator functions function generatefib (n) return coroutine.wrap(function () local a,b = 1, 1 while a <= n do coroutine.yield(a) a, b = b, a+b end end, n) end for i in generatefib(1000) do print(i) end --- NEW FILE: fib.lua --- -- fibonacci function with cache -- very inefficient fibonacci function function fib(n) N=N+1 if n<2 then return n else return fib(n-1)+fib(n-2) end end -- a general-purpose value cache function cache(f) local c={} return function (x) local y=c[x] if not y then y=f(x) c[x]=y end return y end end -- run and time it function test(s,f) N=0 local c=os.clock() local v=f(n) local t=os.clock()-c print(s,n,v,t,N) end n=arg[1] or 24 -- for other values, do lua fib.lua XX n=tonumber(n) print("","n","value","time","evals") test("plain",fib) fib=cache(fib) test("cached",fib) --- NEW FILE: factorial.lua --- -- function closures are powerful -- traditional fixed-point operator from functional programming Y = function (g) local a = function (f) return f(f) end return a(function (f) return g(function (x) local c=f(f) return c(x) end) end) end -- factorial without recursion F = function (f) return function (n) if n == 0 then return 1 else return n*f(n-1) end end end factorial = Y(F) -- factorial is the fixed point of F -- now test it function test(x) io.write(x,"! = ",factorial(x),"\n") end for n=0,16 do test(n) end --- NEW FILE: luac.lua --- -- bare-bones luac in Lua -- usage: lua luac.lua file.lua assert(arg[1]~=nil and arg[2]==nil,"usage: lua luac.lua file.lua") f=assert(io.open("luac.out","wb")) f:write(string.dump(assert(loadfile(arg[1])))) io.close(f) --- NEW FILE: bisect.lua --- -- bisection method for solving non-linear equations delta=1e-6 -- tolerance function bisect(f,a,b,fa,fb) local c=(a+b)/2 io.write(n," c=",c," a=",a," b=",b,"\n") if c==a or c==b or math.abs(a-b)<delta then return c,b-a end n=n+1 local fc=f(c) if fa*fc<0 then return bisect(f,a,c,fa,fc) else return bisect(f,c,b,fc,fb) end end -- find root of f in the inverval [a,b]. needs f(a)*f(b)<0 function solve(f,a,b) n=0 local z,e=bisect(f,a,b,f(a),f(b)) io.write(string.format("after %d steps, root is %.17g with error %.1e, f=%.1e\n",n,z,e,f(z))) end -- our function function f(x) return x*x*x-x-1 end -- find zero in [1,2] solve(f,1,2) --- NEW FILE: env.lua --- -- read environment variables as if they were global variables local f=function (t,i) return os.getenv(i) end setmetatable(getfenv(),{__index=f}) -- an example print(a,USER,PATH) --- NEW FILE: README --- These are simple tests for Lua. Some of them contain useful code. They are meant to be run to make sure Lua is built correctly and also to be read, to see how Lua programs look. Here is a one-line summary of each program: bisect.lua bisection method for solving non-linear equations cf.lua temperature conversion table (celsius to farenheit) echo.lua echo command line arguments env.lua environment variables as automatic global variables factorial.lua factorial without recursion fib.lua fibonacci function with cache fibfor.lua fibonacci numbers with coroutines and generators globals.lua report global variable usage hello.lua the first program in every language life.lua Conway's Game of Life luac.lua bare-bones luac printf.lua an implementation of printf readonly.lua make global variables readonly sieve.lua the sieve of of Eratosthenes programmed with coroutines sort.lua two implementations of a sort function table.lua make table, grouping all data for the same item trace-calls.lua trace calls trace-globals.lua trace assigments to global variables undefined.lua catch "undefined" global variables xd.lua hex dump --- NEW FILE: compat.lua --- ------------------------------------------------------------------- -- Real globals -- _ALERT -- _ERRORMESSAGE -- _VERSION -- _G -- assert -- error -- metatable -- next -- print -- require -- tonumber -- tostring -- type -- unpack ------------------------------------------------------------------- -- collectgarbage -- gcinfo -- globals -- call -> protect(f, err) -- loadfile -- loadstring -- rawget -- rawset -- getargs = Main.getargs ?? function do_ (f, err) if not f then print(err); return end local a,b = pcall(f) if not a then print(b); return nil else return b or true end end function dostring(s) return do_(loadstring(s)) end -- function dofile(s) return do_(loadfile(s)) end ------------------------------------------------------------------- -- Table library local tab = table foreach = tab.foreach foreachi = tab.foreachi getn = tab.getn tinsert = tab.insert tremove = tab.remove sort = tab.sort ------------------------------------------------------------------- -- Debug library local dbg = debug getinfo = dbg.getinfo getlocal = dbg.getlocal setcallhook = function () error"`setcallhook' is deprecated" end setlinehook = function () error"`setlinehook' is deprecated" end setlocal = dbg.setlocal ------------------------------------------------------------------- -- math library local math = math abs = math.abs acos = function (x) return math.deg(math.acos(x)) end asin = function (x) return math.deg(math.asin(x)) end atan = function (x) return math.deg(math.atan(x)) end atan2 = function (x,y) return math.deg(math.atan2(x,y)) end ceil = math.ceil cos = function (x) return math.cos(math.rad(x)) end deg = math.deg exp = math.exp floor = math.floor frexp = math.frexp ldexp = math.ldexp log = math.log log10 = math.log10 max = math.max min = math.min mod = math.mod PI = math.pi --??? pow = math.pow rad = math.rad random = math.random randomseed = math.randomseed sin = function (x) return math.sin(math.rad(x)) end sqrt = math.sqrt tan = function (x) return math.tan(math.rad(x)) end ------------------------------------------------------------------- -- string library local str = string strbyte = str.byte strchar = str.char strfind = str.find format = str.format gsub = str.gsub strlen = str.len strlower = str.lower strrep = str.rep strsub = str.sub strupper = str.upper ------------------------------------------------------------------- -- os library clock = os.clock date = os.date difftime = os.difftime execute = os.execute --? exit = os.exit getenv = os.getenv remove = os.remove rename = os.rename setlocale = os.setlocale time = os.time tmpname = os.tmpname ------------------------------------------------------------------- -- compatibility only getglobal = function (n) return _G[n] end setglobal = function (n,v) _G[n] = v end ------------------------------------------------------------------- local io, tab = io, table -- IO library (files) _STDIN = io.stdin _STDERR = io.stderr _STDOUT = io.stdout _INPUT = io.stdin _OUTPUT = io.stdout seek = io.stdin.seek -- sick ;-) tmpfile = io.tmpfile closefile = io.close openfile = io.open function flush (f) if f then f:flush() else _OUTPUT:flush() end end function readfrom (name) if name == nil then local f, err, cod = io.close(_INPUT) _INPUT = io.stdin return f, err, cod else local f, err, cod = io.open(name, "r") _INPUT = f or _INPUT return f, err, cod end end function writeto (name) if name == nil then local f, err, cod = io.close(_OUTPUT) _OUTPUT = io.stdout return f, err, cod else local f, err, cod = io.open(name, "w") _OUTPUT = f or _OUTPUT return f, err, cod end end function appendto (name) local f, err, cod = io.open(name, "a") _OUTPUT = f or _OUTPUT return f, err, cod end function read (...) local f = _INPUT if type(arg[1]) == 'userdata' then f = tab.remove(arg, 1) end return f:read(unpack(arg)) end function write (...) local f = _OUTPUT if type(arg[1]) == 'userdata' then f = tab.remove(arg, 1) end return f:write(unpack(arg)) end --- NEW FILE: readonly.lua --- -- make global variables readonly local f=function (t,i) error("cannot redefine global variable `"..i.."'",2) end local g={} local G=getfenv() setmetatable(g,{__index=G,__newindex=f}) setfenv(1,g) -- an example rawset(g,"x",3) x=2 y=1 -- cannot redefine `y' |
From: John L. <jr...@us...> - 2005-06-06 23:06:28
|
Update of /cvsroot/wxlua/wxLua/modules/wxluadebug/include In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/wxluadebug/include Added Files: debug.h splttree.h staktree.h Log Message: moved files to the modules directory structure --- NEW FILE: staktree.h --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaStackTree.h // Purpose: Interface to display the lua stack in wxLua // Author: J. Winwood // Created: April 2002 // Copyright: (c) 2002. Lomtick Software. All rights reserved. // Licence: wxWidgets license. ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_LUA_STACKTREE_H_ #define _WX_LUA_STACKTREE_H_ #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "staktree.h" #endif #include "wxlua/defs.h" #include "wxlua/splttree.h" class WXDLLIMPEXP_WXLUA wxLuaStackDataWindow; class WXDLLIMPEXP_WXLUA wxLuaDebugServer; class WXDLLIMPEXP_WXLUA wxLuaInterface; class WXDLLIMPEXP_WXLUA wxLuaDebugData; // ---------------------------------------------------------------------------- // wxLuaStackFrame // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaStackFrame : public wxDialog { public: wxLuaStackFrame(wxWindow *parent, const wxString &title, const wxPoint &pos, const wxSize &size, wxLuaDebugServer *pServer); wxLuaStackFrame(wxWindow *parent, const wxString &title, const wxPoint &pos, const wxSize &size, wxLuaInterface *luaInterface); ~wxLuaStackFrame(); void OnSizeWindow(wxSizeEvent& event); void OnSelectStack(wxCommandEvent &event); void OnItemExpanding(wxTreeEvent &event); void OnCloseDialog(wxCommandEvent &event); void SelectStack(int nCurrentSel); void ItemExpanding(const wxTreeItemId &itemId); void SizeWindow(int nWidth, int nHeight); void FillStackCombobox(const wxLuaDebugData *pDebugData); void FillStackEntry(int nEntry, const wxLuaDebugData *pSortedList); void FillTableEntry(wxTreeItemId itemNode, const wxLuaDebugData *pSortedList); void GetDerivedAndTrackedItems(wxRemotelyScrolledTreeCtrl *treeControl, wxTreeItemId rootItem); private: void Construct(); protected: wxComboBox *m_stackComboBox; wxRemotelyScrolledTreeCtrl *m_treeControl; wxThinSplitterWindow *m_treeSplitter; wxThinSplitterWindow *m_valueSplitter; wxSplitterScrolledWindow *m_scrolledWindow; wxButton *m_dismissButton; wxLuaStackDataWindow *m_firstValueWindow; wxLuaStackDataWindow *m_secondValueWindow; wxLuaInterface *m_luaInterface; wxLuaDebugServer *m_pServer; int m_nCurrentSel; DECLARE_EVENT_TABLE() private: friend class wxLuaStackDataWindow; }; // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- #define idSTACK_FRAME 2000 #define idSTACK_COMBOBOX 2001 #define idSCROLLED_WINDOW 2002 #define idSPLITTER_WINDOW 2003 #define idSTACKTREE_CTRL 2004 #define idVALUE_SPLITTER_WINDOW 2005 #define idFIRST_VALUE_WINDOW 2006 #define idSECOND_VALUE_WINDOW 2007 #define idDISMISS_BUTTON 2008 // ---------------------------------------------------------------------------- // wxLuaStackTree // ---------------------------------------------------------------------------- class wxLuaStackTree : public wxRemotelyScrolledTreeCtrl { DECLARE_CLASS(wxLuaStackTree) public: wxLuaStackTree( wxWindow *parent, wxWindowID id, const wxPoint &pt = wxDefaultPosition, const wxSize &sz = wxDefaultSize, long style = wxTR_HAS_BUTTONS); ~wxLuaStackTree(); void DeleteAllItems(); DECLARE_EVENT_TABLE() private: wxImageList* m_imageList; }; // ---------------------------------------------------------------------------- // wxLuaStackDataWindow // ---------------------------------------------------------------------------- class wxLuaStackDataWindow : public wxTreeCompanionWindow { public: wxLuaStackDataWindow( wxWindow *parent, wxWindowID id = wxID_ANY, const wxPoint &pos = wxDefaultPosition, const wxSize &sz = wxDefaultSize, long style = 0, bool fFirst = true); // Overrides virtual void DrawItem(wxDC &dc, wxTreeItemId id, const wxRect &rect); private: bool m_fFirst; DECLARE_EVENT_TABLE() }; #endif //_WX_LUA_STACKTREE_H_ --- NEW FILE: debug.h --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Implements the debugger end of wxLua debugging session // Author: J. Winwood // Created: June 2003 // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// // Ray Gilbert moved class definitions out of wxLuaDebugServer, wxLuaDebugIO // to allow alternate debugger model // // Original Debugging Model: // wxLuaDebugServer, LuaDebugTarget // The current process acts as a server - debugger (wxLuaDebugServer) // starts a new process which starts up as a client - debuggee (LuaDebugTarget) // that connects back to server process. // // Alternative Debugging Model: // wxLuaDebugService, wxLuaDebuggee, wxLuaDebugger // The current process acts as a server - debuggee (wxLuaDebugService; wxLuaDebuggee). // This service waits for client - debugger to connect. #ifndef WX_LUA_DEBUG_H #define WX_LUA_DEBUG_H #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "debug.h" #endif #include "wx/dynarray.h" #include "wx/treectrl.h" #include "wxlua/defs.h" class WXDLLIMPEXP_WXLUA wxLuaDebugData; // ---------------------------------------------------------------------------- // wxLuaBuffer // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaBuffer : public wxObject { public: wxLuaBuffer(const wxString &fileName, const wxString &buffer); wxString GetBuffer() const { return m_buffer; } wxString GetFileName() const { return m_fileName; } int GetBufferLength() const { return m_buffer.Length(); } private: wxString m_fileName; wxString m_buffer; DECLARE_CLASS(wxLuaBuffer) }; #if wxCHECK_VERSION(2, 5, 0) WX_DEFINE_ARRAY_PTR(wxLuaBuffer *, wxLuaBufferArray); #else WX_DEFINE_ARRAY(wxLuaBuffer *, wxLuaBufferArray); #endif // !wxCHECK_VERSION(2, 5, 0) // ---------------------------------------------------------------------------- // wxLuaDebugDataItem // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaDebugDataItem : public wxTreeItemData { public: wxLuaDebugDataItem(const wxLuaDebugDataItem &debugDataItem); wxLuaDebugDataItem(const wxString &itemName, const wxString &itemType, const wxString &itemValue, const wxString &itemSource, int nReference, int nIndex = 0, bool fExpanded = false); wxString GetName() const { return m_itemName; } wxString GetType() const { return m_itemType; } wxString GetValue() const { return m_itemValue; } wxString GetSource() const { return m_itemSource; } int GetReference() const { return m_nReference; } int GetIndex() const { return m_nIndex; } bool IsExpanded() const { return m_fExpanded; } void SetExpanded(bool fExpanded) { m_fExpanded = fExpanded; } private: wxString m_itemName; wxString m_itemType; wxString m_itemValue; wxString m_itemSource; int m_nReference; int m_nIndex; bool m_fExpanded; }; WX_DEFINE_SORTED_ARRAY(wxLuaDebugDataItem *, wxLuaDebugDataItemArray); // ---------------------------------------------------------------------------- // wxLuaDebugData // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaDebugData : public wxLuaDebugDataItemArray { public: wxLuaDebugData(); virtual ~wxLuaDebugData(); wxLuaDebugData *Clone(); static int SortFunction(wxLuaDebugDataItem *elem1, wxLuaDebugDataItem *elem2 ); }; // ---------------------------------------------------------------------------- // wxLuaInterface // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaInterface { public: wxLuaInterface(lua_State *luaState); virtual ~wxLuaInterface(); wxLuaDebugData *BuildStack(); wxLuaDebugData *BuildStackList(int nEntry); wxLuaDebugData *BuildTableList(int nRef, int nEntry); wxLuaDebugData *GetGlobalData(); lua_State *GetLuaState() const { return m_luaState; } private: int GetStack(int nIndex, lua_Debug *luaDebug); bool GetInfo(const wxString &opts, lua_Debug *luaDebug); wxString GetLocal(lua_Debug *luaDebug, int index); void GetGlobals(); int GetTop(); int Type(int index); double ToNumber(int index); int ToBoolean(int index); wxString ToString(int index); const void *ToPointer(int index); bool IsCFunction(int index); const void *ToCFunction(int index); const void *ToUserData(int index); int GetTag(int index); int GetN(int index); int Ref(); int GetRef(int ref); void Pop(int count); void PushNil(); void PushValue(int index); int Next(int index); bool IsLuaTable(int index) const; wxString GetTableInfo(int index); wxString GetUserDataInfo(int index, bool full = true); static wxString MakeNumber(double dnum); static wxString MakeBoolean(int num); lua_State *m_luaState; wxArrayInt m_references; }; // ---------------------------------------------------------------------------- // wxLuaDebugEvents_Type // ---------------------------------------------------------------------------- enum debugEvents // FIXME prefix wxLUA on these { EVENT_DEBUG_BREAK, EVENT_DEBUG_PRINT, EVENT_DEBUG_ERROR, EVENT_DEBUG_EXIT, EVENT_DEBUG_STACK_ENUM, EVENT_DEBUG_STACK_ENTRY_ENUM, EVENT_DEBUG_TABLE_ENUM, EVENT_DEBUG_EVALUATE_EXPR, EVENT_DEBUG_BREAKPOINT_ADDED, EVENT_DEBUG_BREAKPOINT_REMOVED }; // ---------------------------------------------------------------------------- // wxLuaDebugCommands_Type // ---------------------------------------------------------------------------- enum debugCommands // FIXME prefix wxLUA on these { CMD_ADD_BREAKPOINT, CMD_REMOVE_BREAKPOINT, CMD_CLEAR_ALL_BREAKPOINTS, CMD_RUN_BUFFER, CMD_DEBUG_STEP, CMD_DEBUG_STEPOVER, CMD_DEBUG_STEPOUT, CMD_DEBUG_CONTINUE, CMD_DEBUG_BREAK, CMD_ENUMERATE_STACK, CMD_ENUMERATE_STACK_ENTRY, CMD_ENUMERATE_TABLE_REF, CMD_EVALUATE_EXPR, CMD_RESET, CMD_CLEAR_DEBUG_REFERENCES, CMD_DISABLE_BREAKPOINT, CMD_ENABLE_BREAKPOINT }; // ---------------------------------------------------------------------------- // wxLuaDebuggerBase - Debugger interface base class // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaDebuggerBase : public wxEvtHandler { public: wxLuaDebuggerBase() {} virtual ~wxLuaDebuggerBase() {} virtual bool AddBreakPoint(const wxString &fileName, int lineNumber) = 0; virtual bool RemoveBreakPoint(const wxString &fileName, int lineNumber) = 0; virtual bool ClearAllBreakPoints() = 0; virtual bool Run(const wxString &fileName, const wxString &buffer) = 0; virtual bool Step() = 0; virtual bool StepOver() = 0; virtual bool StepOut() = 0; virtual bool Continue() = 0; virtual bool Break() = 0; virtual bool Reset() = 0; virtual bool EnumerateStack() = 0; virtual bool EnumerateStackEntry(int stackEntry) = 0; virtual bool EnumerateTable(int tableRef, int nIndex, int nItemNode) = 0; virtual bool CleanupDebugReferences() = 0; private: DECLARE_CLASS(wxLuaDebuggerBase) }; // ---------------------------------------------------------------------------- // wxLuaDebugEvent // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaDebugEvent : public wxEvent { public: wxLuaDebugEvent(); wxLuaDebugEvent(int eventType); wxLuaDebugEvent(int eventType, int lineNumber, const wxString &fileName, bool enabledFlag = false); virtual ~wxLuaDebugEvent(); void SetMessage(const wxString &message); void SetDebugData(int nReference, wxLuaDebugData *pDebugData = NULL); int GetLineNumber() const; wxString GetFileName() const; wxString GetMessage() const; int GetReference() const; const wxLuaDebugData *GetDebugData() const; bool GetEnabledFlag() const; protected: virtual wxEvent* Clone() const; private: bool m_fHasMessage; bool m_fEnabledFlag; int m_lineNumber; wxString m_fileName; wxString m_strMessage; int m_nReference; wxLuaDebugData *m_pDebugData; DECLARE_DYNAMIC_CLASS(wxLuaDebugEvent) }; typedef void (wxEvtHandler::*wxLuaDebugEventFunction)(wxLuaDebugEvent&); // FIXME prefix wxLUA on these BEGIN_DECLARE_EVENT_TYPES() DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_CLIENT_CONNECTED, 2510) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_BREAK, 2511) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_PRINT, 2512) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_ERROR, 2513) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_EXIT, 2514) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_STACK_ENUM, 2515) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_STACK_ENTRY_ENUM, 2516) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_TABLE_ENUM, 2517) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_EVALUATE_EXPR, 2518) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_STARTDEBUGGER, 2519) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_STOPDEBUGGER, 2520) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_BREAKPOINT_ADDED, 2521) DECLARE_LOCAL_EVENT_TYPE(wxEVT_DEBUG_BREAKPOINT_REMOVED, 2522) END_DECLARE_EVENT_TYPES() #define EVT_DEBUG_CLIENT_CONNECTED(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_BREAK, id, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_BREAK(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_BREAK, id, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_PRINT(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_PRINT, id, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_ERROR(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_ERROR, id, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_EXIT(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_EXIT, id, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_STACK_ENUM(fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_STACK_ENUM, -1, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_STACK_ENTRY_ENUM(fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_STACK_ENTRY_ENUM, -1, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_TABLE_ENUM(fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_TABLE_ENUM, -1, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_EVALUATE_EXPR(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_EVALUATE_EXPR, id, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_STARTDEBUGGER(fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_STARTDEBUGGER, -1, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_STOPDEBUGGER(fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_STOPDEBUGGER, -1, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_BREAKPOINT_ADDED(fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_BREAKPOINT_ADDED, -1, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #define EVT_DEBUG_BREAKPOINT_REMOVED(fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_DEBUG_BREAKPOINT_REMOVED, -1, -1, (wxObjectEventFunction) (wxEventFunction) (wxLuaDebugEventFunction) & fn, (wxObject *) NULL), #endif // WX_LUA_DEBUG_H --- NEW FILE: splttree.h --- ///////////////////////////////////////////////////////////////////////////// // Name: splittree.h // Purpose: Classes to achieve a remotely-scrolled tree in a splitter // window that can be scrolled by a scrolled window higher in the // hierarchy // Author: Julian Smart // Modified by: J. Winwood, to fix a few bugs and also add a second // splitter and scrolled window (three columns rather than two). // Created: 8/7/2000 // Copyright: (c) Julian Smart // (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_SPLITTREE_H_ #define _WX_SPLITTREE_H_ #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "splttree.h" #endif #include "wxlua/defs.h" #include "wx/treectrl.h" #include "wx/splitter.h" #include "wx/scrolwin.h" class WXDLLIMPEXP_WXLUA wxRemotelyScrolledTreeCtrl; class WXDLLIMPEXP_WXLUA wxThinSplitterWindow; class WXDLLIMPEXP_WXLUA wxSplitterScrolledWindow; /* * wxRemotelyScrolledTreeCtrl * * This tree control disables its vertical scrollbar and catches scroll * events passed by a scrolled window higher in the hierarchy. * It also updates the scrolled window vertical scrollbar as appropriate. */ class WXDLLIMPEXP_WXLUA wxRemotelyScrolledTreeCtrl : public wxTreeCtrl { public: wxRemotelyScrolledTreeCtrl(wxWindow* parent, wxWindowID id, const wxPoint &pt = wxDefaultPosition, const wxSize &sz = wxDefaultSize, long style = wxTR_HAS_BUTTONS); ~wxRemotelyScrolledTreeCtrl(); //// Events void OnSize(wxSizeEvent& event); void OnExpand(wxTreeEvent& event); void OnScroll(wxScrollWinEvent& event); void OnPaint(wxPaintEvent& event); void OnSelChanged(wxTreeEvent& event); //// Overrides // Override this in case we're using the generic tree control. // Calls to this should disable the vertical scrollbar. // Number of pixels per user unit (0 or -1 for no scrollbar) // Length of virtual canvas in user units // Length of page in user units virtual void SetScrollbars(int pixelsPerUnitX, int pixelsPerUnitY, int noUnitsX, int noUnitsY, int xPos = 0, int yPos = 0, bool noRefresh = FALSE ); // In case we're using the generic tree control. // Get the view start virtual void GetViewStart(int *x, int *y) const; // In case we're using the generic tree control. virtual void PrepareDC(wxDC& dc); // In case we're using the generic tree control. virtual int GetScrollPos(int orient) const; //// Helpers void HideVScrollbar(); // Calculate the tree overall size so we can set the scrollbar // correctly void CalcTreeSize(wxRect& rect); void CalcTreeSize(const wxTreeItemId& id, wxRect& rect); // Adjust the containing wxScrolledWindow's scrollbars appropriately void AdjustRemoteScrollbars(); // Find the scrolled window that contains this control wxScrolledWindow* GetScrolledWindow() const; // Scroll to the given line (in scroll units where each unit is // the height of an item) void ScrollToLine(int posHoriz, int posVert); void DeleteAllItems(); //// Accessors // The companion window is one which will get notified when certain // events happen such as node expansion void SetCompanionWindows(wxWindow* firstCompanion, wxWindow* secondCompanion = NULL) { m_firstCompanionWindow = firstCompanion; m_secondCompanionWindow = secondCompanion; } wxWindow* GetFirstCompanionWindow() const { return m_firstCompanionWindow; } wxWindow* GetSecondCompanionWindow() const { return m_secondCompanionWindow; } DECLARE_EVENT_TABLE() protected: wxWindow *m_firstCompanionWindow; wxWindow *m_secondCompanionWindow; bool m_drawRowLines; wxTreeItemId &m_lastTreeItemId; private: DECLARE_CLASS(wxRemotelyScrolledTreeCtrl) }; /* * wxTreeCompanionWindow * * A window displaying values associated with tree control items. */ class WXDLLIMPEXP_WXLUA wxTreeCompanionWindow: public wxWindow { public: DECLARE_CLASS(wxTreeCompanionWindow) wxTreeCompanionWindow(wxWindow* parent, wxWindowID id = -1, const wxPoint& pos = wxDefaultPosition, const wxSize& sz = wxDefaultSize, long style = 0); ~wxTreeCompanionWindow(); //// Overrides virtual void DrawItem(wxDC& dc, wxTreeItemId id, const wxRect& rect); //// Events void OnPaint(wxPaintEvent& event); void OnScroll(wxScrollWinEvent& event); void OnExpand(wxTreeEvent& event); void OnSelChanged(wxTreeEvent& event); //// Operations //// Accessors wxRemotelyScrolledTreeCtrl* GetTreeCtrl() const { return m_treeControl; } void SetTreeCtrl(wxRemotelyScrolledTreeCtrl* treeControl) { m_treeControl = treeControl; } //// Data members protected: wxRemotelyScrolledTreeCtrl *m_treeControl; DECLARE_EVENT_TABLE() }; /* * wxThinSplitterWindow * * Implements a splitter with a less obvious sash * than the usual one. */ class WXDLLIMPEXP_WXLUA wxThinSplitterWindow : public wxSplitterWindow { public: DECLARE_DYNAMIC_CLASS(wxThinSplitterWindow) wxThinSplitterWindow(wxWindow* parent, wxWindowID id = -1, const wxPoint& pos = wxDefaultPosition, const wxSize& sz = wxDefaultSize, long style = wxSP_3D | wxCLIP_CHILDREN); //// Overrides void SizeWindows(); // Tests for x, y over sash. Overriding this allows us to increase // the tolerance. bool SashHitTest(int x, int y, int tolerance = 2); void DrawSash(wxDC& dc); //// Events void OnSize(wxSizeEvent& event); //// Operations //// Accessors //// Data members protected: DECLARE_EVENT_TABLE() }; /* * wxSplitterScrolledWindow * * This scrolled window is aware of the fact that one of its * children is a splitter window. It passes on its scroll events * (after some processing) to both splitter children for them * scroll appropriately. */ class wxSplitterScrolledWindow: public wxScrolledWindow { public: DECLARE_DYNAMIC_CLASS(wxSplitterScrolledWindow) wxSplitterScrolledWindow(wxWindow* parent, wxWindowID id = -1, const wxPoint &pos = wxDefaultPosition, const wxSize &sz = wxDefaultSize, long style = 0); //// Overrides //// Events void OnScroll(wxScrollWinEvent& event); void OnSize(wxSizeEvent& event); //// Operations //// Accessors //// Data members public: DECLARE_EVENT_TABLE() }; #endif // _SPLITTREE_H_ |
From: John L. <jr...@us...> - 2005-06-06 23:06:28
|
Update of /cvsroot/wxlua/wxLua/modules/wxlua/include In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/wxlua/include Added Files: callback.h defs.h internal.h interp.h library.h wxlua.h Log Message: moved files to the modules directory structure --- NEW FILE: interp.h --- ///////////////////////////////////////////////////////////////////////////// // Name: wxLuaInterpreter // Purpose: A simple class for a C++ wxWidgets program to embed wxLua // Author: John Labenski // Modified by: // Created: 11/05/2002 // Copyright: (c) John Labenski // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_LUA_INTERPRETER_H_ #define _WX_LUA_INTERPRETER_H_ #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "interp.h" #endif #include "wxlua/defs.h" extern "C" { #include "lua.h" // for DebugHook defines // To not include "lua.h" use these //typedef struct lua_State lua_State; //typedef struct lua_Debug lua_Debug; //typedef int (*lua_CFunction)(lua_State *); } class WXDLLEXPORT wxEvtHandler; class wxLuaEvent; class wxLuaStateVariables; class wxLuaInterpreter; #include "wx/hashmap.h" WX_DECLARE_VOIDPTR_HASH_MAP( wxLuaInterpreter *, wxHashMapLuaInterpreter ); extern wxHashMapLuaInterpreter s_wxHashMapLuaInterpreter; //----------------------------------------------------------------------------- // Extra wxLua helpers that use the lua_State to find owner wxLuaInterpreter //----------------------------------------------------------------------------- extern wxLuaInterpreter *wxFindLuaInterpreter(lua_State *L); extern wxLuaStateVariables *wxFindLuaStateVariables(lua_State *L); //----------------------------------------------------------------------------- // wxLuaInterpreter // // notes : create instance, call RunString("some lua code") // Events are sent to the evthander if !null with the given id # //----------------------------------------------------------------------------- class wxLuaInterpreter : public wxObject { public: // default constructor - must call Create in order to use wxLuaInterpreter(); // Create a wxLua instance, handler and id can be null/wxID_ANY for don't care wxLuaInterpreter(wxEvtHandler *handler, wxWindowID id = wxID_ANY); wxLuaInterpreter(lua_State *L, wxEvtHandler *handler, wxWindowID id = wxID_ANY); virtual ~wxLuaInterpreter(); // (re)Create a new wxLua instance, handler and id can be null/wxID_ANY for don't care // don't forget to ShutDown the last one first (if you want to) bool Create(lua_State *L, wxEvtHandler *handler=NULL, wxWindowID id = wxID_ANY); bool Create(wxEvtHandler *handler=NULL, wxWindowID id = wxID_ANY) { return Create(NULL, handler, id); } // destroy and cleanup the interpreter, returns sucess // if 'force' then make sure all wxWindows are destroyed. bool Destroy(bool force = TRUE); // has the interpreter been sucessfully created bool Ok() const; // Set the event handler that the events will be sent to, can be null void SetEventHandler(wxEvtHandler *evtHandler); wxEvtHandler *GetEventHandler() const; // Get/Set the id that the events will be sent with void SetId(int id); int GetId() const; // Run a lua file int RunFile(const wxString &fileName); // Run a string that contains lua code int RunString(const wxString &script, const wxString& name = wxEmptyString); // Run a char array #include(d) from bin2c compilation int RunBuffer(const unsigned char buf[], size_t size, const wxString &name = wxT("= lua")); // Is a program running now bool IsRunning() const; // Break a currently running lua program void Break(const wxString &message = wxT("Interpreter stopped")); // has Break() been called bool GetBreak() const; wxString GetBreakMessage() const; // Have lua run an internal hook function with this mask // hook = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT // Every count hook mask a wxEVT_LUA_DEBUG_HOOK event is sent if send_debug_evt // if yield > 0 then wxYield is called every yield milliseconds // I don't know what resonable values are // turn the hook off with count < 1 void SetLuaDebugHook(int count = 1000, int yield = 50, bool send_debug_evt = FALSE, int hook = LUA_MASKCOUNT); int GetLuaDebugHookCount() const; int GetLuaDebugHookYield() const; bool GetLuaDebugHookSendEvt() const; int GetLuaDebugHook() const; // registers a new function for Lua void RegisterFunction(lua_CFunction func, const wxString &funcName); // Get a pointer to the lua_State that "is" lua lua_State *GetLuaState() const; // Get a pointer to additional wxLua variables used for this lua_State wxLuaStateVariables *GetStateVariables() const; // ----------------------------------------------------------------------- // implementation // generic function to generate a wxEVT_LUA_ERROR with the string message void DisplayError( const wxString &errorMsg ); // checks return val of 'lua_load' and `lua_pcall', if error send wxEVT_LUA_ERROR bool CheckRunError(int rc); // internally used so debug hook events are sent no more often than yield time unsigned long GetLastLuaDebugHookTime() const; void SetLastLuaDebugHookTime(unsigned long t); void SendEvent( wxLuaEvent &event ) const; // operators operator lua_State*() { return GetLuaState(); } protected: bool m_is_running; unsigned long m_last_debug_hook_time; bool m_user_break; wxString m_break_msg; wxLuaStateVariables *m_luaStateVariables; lua_State *m_lua_State; bool m_luaAllocated; int m_lua_debug_hook_count; int m_lua_debug_hook_yield; bool m_lua_debug_hook_send_evt; int m_lua_debug_hook; wxEvtHandler *m_evtHandler; int m_id; private : void Init(); DECLARE_ABSTRACT_CLASS(wxLuaInterpreter) }; //----------------------------------------------------------------------------- // wxLuaEvent //----------------------------------------------------------------------------- class wxLuaEvent: public wxNotifyEvent { public: wxLuaEvent(wxEventType commandType = wxEVT_NULL, wxWindowID id = wxID_ANY, wxLuaInterpreter *intrepreter=NULL); wxLuaEvent( const wxLuaEvent &event ) : wxNotifyEvent(event) { m_stop_interpreter = event.m_stop_interpreter; m_luaInterpreter = event.m_luaInterpreter; m_lua_Debug = event.m_lua_Debug; } virtual wxEvent *Clone() const { return new wxLuaEvent(*this); } // use GetString method to retrieve info // Get the line number in the code, -1 if unknown int GetLineNum() const { return m_commandInt; } wxLuaInterpreter *GetLuaInterpreter() const { return m_luaInterpreter; } void SetLuaInterpreter(wxLuaInterpreter *interp) { m_luaInterpreter = interp; } lua_State *GetLuaState() const { return m_luaInterpreter ? m_luaInterpreter->GetLuaState() : NULL; } // non null only for EVT_LUA_DEBUG_HOOK lua_Debug *GetLuaDebug() const { return m_lua_Debug; } // If called from a wxEVT_LUA_DEBUG_HOOK the interpreter will stop void StopInterpreter(bool stop) { m_stop_interpreter = stop; } bool m_stop_interpreter; wxLuaInterpreter *m_luaInterpreter; lua_Debug *m_lua_Debug; }; BEGIN_DECLARE_EVENT_TYPES() DECLARE_LOCAL_EVENT_TYPE(wxEVT_LUA_CREATION, 0) // a wxLuaInterpreter is being created DECLARE_LOCAL_EVENT_TYPE(wxEVT_LUA_CONSOLE, 0) // print statements and such, check GetString() DECLARE_LOCAL_EVENT_TYPE(wxEVT_LUA_WARNING, 0) // unused, lua doesn't seem to warn for anything DECLARE_LOCAL_EVENT_TYPE(wxEVT_LUA_ERROR, 0) // error occurred, check GetString() DECLARE_LOCAL_EVENT_TYPE(wxEVT_LUA_DEBUG_HOOK, 0) // see LuaDebugHook function DECLARE_LOCAL_EVENT_TYPE(wxEVT_LUA_SHUTDOWN, 0) // unused, I used this in some other interpreter, not sure why it'd be useful END_DECLARE_EVENT_TYPES() typedef void (wxEvtHandler::*wxLuaEventFunction)(wxLuaEvent&); #define EVT_LUA_CREATION(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_LUA_CREATION, id, wxID_ANY, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxNotifyEventFunction) (wxLuaEventFunction) & fn, (wxObject *) NULL ), #define EVT_LUA_CONSOLE(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_LUA_CONSOLE, id, wxID_ANY, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxNotifyEventFunction) (wxLuaEventFunction) & fn, (wxObject *) NULL ), #define EVT_LUA_WARNING(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_LUA_WARNING, id, wxID_ANY, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxNotifyEventFunction) (wxLuaEventFunction) & fn, (wxObject *) NULL ), #define EVT_LUA_ERROR(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_LUA_ERROR, id, wxID_ANY, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxNotifyEventFunction) (wxLuaEventFunction) & fn, (wxObject *) NULL ), #define EVT_LUA_DEBUG_HOOK(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_LUA_DEBUG_HOOK, id, wxID_ANY, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxNotifyEventFunction) (wxLuaEventFunction) & fn, (wxObject *) NULL ), #define EVT_LUA_SHUTDOWN(id, fn) DECLARE_EVENT_TABLE_ENTRY(wxEVT_LUA_SHUTDOWN, id, wxID_ANY, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxNotifyEventFunction) (wxLuaEventFunction) & fn, (wxObject *) NULL ), #endif // _WX_LUA_INTERPRETER_H_ --- NEW FILE: wxlua.h --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Interface to wxLua // Author: J Winwood // Created: 14/11/2001 // Copyright: (c) 2001-2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef WX_LUA_H #define WX_LUA_H extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include "wxlua/defs.h" // If you're using stdcall in Lua, then override this with // "LUACALL = __stdcall" in your makefile or project. #ifndef LUACALL #define LUACALL #endif // This is the function you need to call to initialize wxLua void LUACALL RegisterWxLua(lua_State *L, bool registerTypes = true); // Two cases where you might multiply call RegisterWxLua: // 1. You have several lua_State values. Then registerTypes // should always be true. // 2. You have only one lua_State, but have swapped out // the global table. Then you want to set registerTypes to false // for second and subsequent registrations. int LUACALL RegisterWxLuaFunctions(lua_State *L, bool registerTypes = true); // Call this on application exit, to let wxLua tidy up void LUACALL CleanupWxLua(lua_State *L, bool closeLua = true); // Given a lua tag, return the corresponding tag name const char * LUACALL GetLuaTagName(lua_State *L, int nTag); // Used to create a set of standard bitmaps for wxLua int LUACALL CreateStandaloneBitmaps(lua_State *luaState); #endif // WX_LUA_H --- NEW FILE: defs.h --- /////////////////////////////////////////////////////////////////////////////// // Name: defs.h // Purpose: wxLua common defines // Author: John Labenski // Modified by: // Created: 5/28/2005 // RCS-ID: // Copyright: (c) John Labenski // Licence: wxWidgets licence /////////////////////////////////////////////////////////////////////////////// #ifndef __WX_WXLUADEFS_H__ #define __WX_WXLUADEFS_H__ #include "wx/defs.h" extern "C" { typedef struct lua_State lua_State; typedef struct lua_Debug lua_Debug; } // ---------------------------------------------------------------------------- // WXDLLIMPEXP macros // ---------------------------------------------------------------------------- // These are our DLL macros (see the contrib libs like wxPlot) #ifdef WXMAKINGDLL_WXLUA #define WXDLLIMPEXP_WXLUA WXEXPORT #define WXDLLIMPEXP_DATA_WXLUA(type) WXEXPORT type #elif defined(WXUSINGDLL) #define WXDLLIMPEXP_WXLUA WXIMPORT #define WXDLLIMPEXP_DATA_WXLUA(type) WXIMPORT type #else // not making nor using DLL #define WXDLLIMPEXP_WXLUA #define WXDLLIMPEXP_DATA_WXLUA(type) type #endif #endif // __WX_WXLUADEFS_H__ --- NEW FILE: callback.h --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Class to let hook back wx events to Lua // Author: Francis Irving // Created: 21/01/2002 // Copyright: (c) 2002 Creature Labs. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef WX_LUA_CALLBACK_H #define WX_LUA_CALLBACK_H #include "wxlua/defs.h" class WXDLLIMPEXP_WXLUA wxLuaStateVariables; // ---------------------------------------------------------------------------- // wxLuaCallback - proxy class to pass a reference to a lua function // through the wxWidgets event system. // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaCallback : public wxEvtHandler { public: wxLuaCallback( lua_State *state, int theRoutine, wxWindowID id, wxEventType eventType, wxEvtHandler *pHandler ); virtual ~wxLuaCallback(); void ClearState() { m_luaState = NULL; } void ClearStateVars() { m_luaStateVars = NULL; } lua_State* GetLuaState() const { return m_luaState; } int GetId() const { return m_id; } wxEventType GetEventType() const { return m_eventType; } wxEvtHandler *GetEvtHandler() const { return m_pHandler; } // central event handler void EventHandler(wxEvent& event); protected: // event handler dispatcher back to Lua void CallFunction(wxEvent *pEvent); // reference to the routine to call int m_routine; // Lua state instance lua_State *m_luaState; // store the state variables since we're added to a list of callbacks. // The lua_State is NULLed when the window (handler) is destroyed, // but we still want to remove us from the state vars callback list. wxLuaStateVariables *m_luaStateVars; wxEvtHandler *m_pHandler; wxWindowID m_id; wxEventType m_eventType; private: DECLARE_CLASS(wxLuaCallback); }; // ---------------------------------------------------------------------------- // LuaDestroyCallback - proxy class to handle the destruction of wxWindow // derived objects // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaDestroyCallback : public wxEvtHandler { public: wxLuaDestroyCallback( lua_State *state, wxWindowID id, wxEvtHandler *pHandler, int iTag); virtual ~wxLuaDestroyCallback(); void ClearState() { m_luaState = NULL; } void ClearStateVars() { m_luaStateVars = NULL; } lua_State* GetLuaState() const { return m_luaState; } wxEvtHandler* GetEvtHandler() const { return m_pHandler; } // central event handler void EventHandler(wxWindowDestroyEvent& event); protected: void OnDestroy(); // Lua state instance lua_State *m_luaState; // store the state variables see wxLuaCallback for reasoning wxLuaStateVariables *m_luaStateVars; wxEvtHandler *m_pHandler; int m_id; private: DECLARE_CLASS(wxLuaDestroyCallback) }; #endif //WX_LUA_CALLBACK_H --- NEW FILE: library.h --- //////////////////////////////////////////////////////////////////////////////// // Purpose: Provides a wxApp that you should derive yours from to use wxLua // Author: Francis Irving // Created: 16/01/2002 // Modified: J. Winwood. April 2002. Added debugging interfaces // Copyright: (c) 2002 Creature Labs. All rights reserved. // Copyright: (c) 2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence //////////////////////////////////////////////////////////////////////////////// #ifndef WX_LUA_LIBRARY_H #define WX_LUA_LIBRARY_H #ifdef __GNUG__ #pragma interface "library.h" #endif #include "wxlua/defs.h" #include "wx/utils.h" #include "wx/app.h" class WXDLLIMPEXP_WXLUA wxLuaDebugEvent; class WXDLLIMPEXP_WXLUA wxLuaStackFrame; // ---------------------------------------------------------------------------- // wxLuaHandler - Allow for Custom Lua Handler (an alternative to wxLuaApp) // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaHandler { public: wxLuaHandler(); virtual ~wxLuaHandler(); virtual void AddPendingEvent(wxEvent& event) = 0; virtual bool ProcessEvent(wxEvent& event) = 0; virtual void SetStackFrame(wxLuaStackFrame *pStackFrame) = 0; virtual void DisplayError(const wxString &strError) const = 0; void EnterLuaCriticalSection() { m_luaCriticalSection.Enter(); } void LeaveLuaCriticalSection() { m_luaCriticalSection.Leave(); } public: static wxLuaHandler* sm_luahandler; wxCriticalSection m_luaCriticalSection; }; // Lua App/Debugger Interface wxLuaHandler& wxGetLuaHandler(); #endif //WX_LUA_LIBRARY_H --- NEW FILE: internal.h --- ///////////////////////////////////////////////////////////////////////////// // Purpose: Internals of wxLua // Author: J Winwood // Created: 14/11/2001 // Copyright: (c) 2001-2002 Lomtick Software. All rights reserved. // Licence: wxWidgets licence ///////////////////////////////////////////////////////////////////////////// #ifndef WX_LUA_INTERNALS_H #define WX_LUA_INTERNALS_H #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "internal.h" #endif #include "wx/treectrl.h" #include "wxlua/defs.h" #include "wxlua/wxlua.h" #include "wxlua/interp.h" extern "C" { #include "lualib.h" #include "lauxlib.h" } // change the name of some defines to avoid clashes // with standard lua functions. #define wxFileRead read #define wxFileWrite write #define wxFileReadWrite read_write #define wxFileWriteAppend write_append #define wxDataObjectGet wxDataObject::Get #define wxDataObjectSet wxDataObject::Set #if defined(__WXGTK__) #define wxPlatformGTK wxVERSION_NUMBER #elif defined(__WXMSW__) #define wxPlatformWindows wxVERSION_NUMBER #elif defined(__WXMAC__) #define wxPlatformMac wxVERSION_NUMBER #endif // ---------------------------------------------------------------------------- // wxLua type enums and structs // ---------------------------------------------------------------------------- enum LuaType // The type of a Lua method { LuaDelete = 1, // gc routine LuaConstructor = 2, // constructor LuaDestructor = 4, // destructor (not used) LuaMethod = 8, // class method LuaGlobal = 16, // global method (not really related to the class) LuaGetProp = 32, LuaSetProp = 64 }; struct WXLUAMETHOD // defines a LUA method or property { LuaType type; // type (one of the above enumeration values) const char *name; // name of the method or property lua_CFunction func; // function that implements the method or property int params; // number of params to the method (required + optional) int required; // number of required params }; struct WXLUACLASS // defines a LUA class interface { const char *name; // name of the class WXLUAMETHOD *methods; // pointer to methods for this class int num_methods; // number of methods int baseclassindex; // index in the class list to the base class wxClassInfo *pClassInfo; // pointer to the wxClassInfo associated with this class int *class_tag; // tag for user data allocated by ourselves // and therefore needs gc. }; struct WXLUADEFINE // defines a wxWidgets define for wxLua { const char *name; // name double value; // numeric value }; struct WXLUASTRING // defines a wxWidgets define for wxLua { const char *name; // name const wxChar *value; // string value }; struct WXLUAEVENT // defines a wxWidgets Event for wxLua { const int *eventType; // new wxWidgets event type const char *eventName; // name of the event int *eventClassTag; // lua class tag }; struct WXLUAOBJECT // Defines a wxWidgets object or pointer for wxLua { const void *objPtr; // a pointer to the object or pointer const void **pObjPtr; // a pointer to the object or pointer const char *objName; // the name of the object or pointer int *objClassTag; // the class tag of the object or pointer. }; // Functions defined in wxLuaWrap.cpp extern WXLUACLASS *GetClassList(size_t &count); extern WXLUADEFINE *GetDefineList(size_t &count); extern WXLUASTRING *GetStringList(size_t &count); extern WXLUAEVENT *GetEventList(size_t &count); extern WXLUAOBJECT *GetObjectList(size_t &count); // ---------------------------------------------------------------------------- // wxLuaStateVariables - state variables for a wxLua instance // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaStateVariables { public: wxLuaStateVariables(); ~wxLuaStateVariables(); void ClearCallbacks(); bool m_typesRegistered; // wxWidgets classes are registed to lua int m_startTag; // The first wxLua allocated lua tag int m_lastTag; // The last wxLua lua tag of registered classes int m_functionTag; // The lua tag for function objects. int m_wxLuaTable; // The lua tag for the wxLua private tables int m_wxNull; // The lua tag for wxNull (for NULL pointers) int m_wxDeleteTable; // The lua tag for the wxWindow destroy tracking table wxEventType m_inEventType; // wxEventType set when in event, else -1 wxHashTable *m_pDerivedList; // The list of derived objects. wxHashTable *m_pTrackedList; // The list of tracked objects. wxList *m_pAppHandlerList; // The list of event objects associated with the application object wxList *m_pDestroyHandlerList; // The list of wxLuaDestroyCallbacks installed wxList *m_pWindowList; // The list of all wxWindow objects, wxWidgets will delete these // but for an embedded program they must be deleted before // deleting shutting down the interpreter, else they dangle // used in ~wxLuaInterpreter wxArrayInt m_usedIndexes; }; // GET_LUASTATEVARS_XXX returns an instance of the wxLuaStateVariables for the // corresponding lua_State extern wxLuaStateVariables *wxFindLuaStateVariables(lua_State *L); extern wxLuaInterpreter *wxFindLuaInterpreter(lua_State *L); // these follow wxCHECK_MSG/RET semantics #define GET_LUASTATEVARS_MSG(L, return_val) \ wxLuaStateVariables *stateVars = wxFindLuaStateVariables(L); \ wxCHECK_MSG(stateVars, return_val, wxT("invalid wxLuaInterpreter")); #define GET_LUASTATEVARS_RET(L) \ wxLuaStateVariables *stateVars = wxFindLuaStateVariables(L); \ wxCHECK_RET(stateVars, wxT("invalid wxLuaInterpreter")); // ---------------------------------------------------------------------------- // SmartStringArray - A class to wrap an array of wxStrings with an // automatic destructor for making binding easier // ---------------------------------------------------------------------------- class SmartStringArray { public: SmartStringArray() : m_choices(NULL) { } ~SmartStringArray() { if (m_choices != NULL) delete[] m_choices; } void operator =(wxString *choices) { m_choices = choices; } private: wxString *m_choices; }; // ---------------------------------------------------------------------------- // SmartIntArray - A class to wrap an array of ints with an // automatic destructor for making binding easier // ---------------------------------------------------------------------------- class SmartIntArray { public: SmartIntArray() : m_choices(NULL) { } ~SmartIntArray() { if (m_choices != NULL) delete[] m_choices; } void operator =(int *choices) { m_choices = choices; } private: int *m_choices; }; // ---------------------------------------------------------------------------- // DECLARE_ENCAPSULATION and IMPLEMENT_ENCAPSULATION // Declare the macros used to define and implement classes that // wrap non-wxObject derived pointers used by wxLua. // ---------------------------------------------------------------------------- #define DECLARE_ENCAPSULATION(theObject) \ class theObject; \ void LUACALL addToTrackedMemoryList(lua_State *, theObject *); \ class theObject##Object : public wxObject \ { \ public: \ theObject##Object(theObject *p_##theObject); \ ~theObject##Object(); \ private: \ theObject *m_p##theObject; \ }; #define IMPLEMENT_ENCAPSULATION(theObject) \ theObject##Object::theObject##Object(theObject *p##theObject) : \ m_p##theObject(p##theObject) \ { \ } \ theObject##Object::~theObject##Object() \ { \ if (m_p##theObject != NULL) \ delete m_p##theObject; \ } \ void LUACALL addToTrackedMemoryList(lua_State *L, theObject *p##theObject) \ { \ GET_LUASTATEVARS_RET(L) \ if (stateVars->m_pTrackedList == NULL) \ stateVars->m_pTrackedList = new wxHashTable(wxKEY_INTEGER); \ if (stateVars->m_pTrackedList != NULL) \ stateVars->m_pTrackedList->Put((int)p##theObject, new theObject##Object(p##theObject)); \ } // Add a wxWidgets object to the list of tracked objects for // garbage collection purposes. void LUACALL addToTrackedMemoryList(lua_State *L, wxObject *); bool LUACALL removeTrackedMemory(lua_State *L, void *pObject, bool fDelete = true); void LUACALL addToTrackedWindowList(lua_State *L, wxWindow *); // ---------------------------------------------------------------------------- // wxLuaObject - wraps a reference to a Lua object inside a wxObject-derived // class so that it can be used for user data, etc. // Extended to support the wxValidator classes. // ---------------------------------------------------------------------------- class WXDLLIMPEXP_WXLUA wxLuaObject : public wxObject { public: wxLuaObject(); wxLuaObject(lua_State *, int iParam, int iRef = 1); ~wxLuaObject(); bool GetObject(); void SetObject(int iParam); void SetObject(lua_State *, int iParam); bool *GetBoolPtr(); int *GetIntPtr(); wxString *GetStringPtr(); wxArrayInt *GetArrayPtr(); int GetAllocationFlags() const; void ModifyAllocationFlags(int iValue); lua_State *GetLuaState() const { return m_luaState; } private: lua_State *m_luaState; int m_iReference; bool m_allocatedBool; bool m_bool; bool m_allocatedInt; int m_int; bool m_allocatedString; wxString m_string; bool m_allocatedArray; wxArrayInt m_arrayInt; DECLARE_DYNAMIC_CLASS(wxLuaObject) }; class wxLuaTreeItemData : public wxTreeItemData { private: double m_value; public: wxLuaTreeItemData(double value = 0) : m_value(value) {} double GetValue() const { return m_value; } void SetValue(double value) { m_value = value; } }; // ---------------------------------------------------------------------------- // C lua helper functions // ---------------------------------------------------------------------------- // get a user data type (either allocated by us if the tag is iTagS otherwise // system allocated iTagP. if the data type does not have the correct tag, // or if the parameter iParam is nil, NULL is returned. // otherwise an error occurs void * LUACALL getuserdatatype(lua_State *, int iParam, int iTag); // set a user data type void LUACALL pushuserdatatype(lua_State *, int iTag, const void *data); // helper functions to get numbers, booleans and strings safer const char * LUACALL getstringtype(lua_State *, int iParam); bool LUACALL getbooleantype(lua_State *, int iParam); long LUACALL getenumerationtype(lua_State *, int iParam); double LUACALL getnumbertype(lua_State *, int iParam); // convert a parameter which is presumably a table into a string array. // returns the number of strings in the array in count. // the return value may need to be deleted. wxString * LUACALL tostringarray(lua_State *, int iParam, int &count); // convert a parameter which is presumably a table into a character pointer array. // returns the number of character strings in the array in count. // the return value may need to be deleted. const char ** LUACALL tochararray(lua_State *, int iParam, int &count); // convert a parameter which is presumably a wxArrayString reference a string array. // returns the table containing the strings on the Lua stack. // returns the number of items in the table int LUACALL tostringtable(lua_State *, wxArrayString &files); int LUACALL tointtable(lua_State *L, const wxArrayInt &table); // convert a parameter which is presumably a table into a integer array. // returns the number of ints in the array in count. // the return value may need to be deleted. int * LUACALL tointarray(lua_State *, int iParam, int &count); int LUACALL toarrayint(lua_State *L, int iParam, wxArrayInt &intArray); // register all the generated classes void LUACALL registerGeneratedClasses(lua_State *L, int tableOffset, bool registerTypes); // register non-generated functions and types void LUACALL registerOthers(lua_State *L, bool registerTypes); // free memory associated with the lua call class. int LUACALL functionGarbageCollect(lua_State *L); // memory deallocation function int LUACALL garbageCollect(lua_State *L); // lua 'set table' tag method handler int LUACALL setTableFunc(lua_State *L); // lua 'get table' tag method handler int LUACALL getTableFunc(lua_State *L); // call a Lua function int LUACALL callFunction(lua_State *L); // global function in Lua for wiring int LUACALL ConnectEvent(lua_State *L); int LUACALL DisconnectEvent(lua_State *L); // get the method or 'get' property for the class at cpIndex WXLUAMETHOD * LUACALL getLuaMethod(WXLUACLASS *pClass, const char *cpIndex, bool &isProperty); // get the property for the class at cpIndex WXLUAMETHOD * LUACALL getLuaProperty(WXLUACLASS *pClass, const char *cpIndex, bool isSet); // get the derived method for the class cpIndex lua_State * LUACALL getDerivedMethod(void *pObject, const char *method, lua_State *L = NULL); int LUACALL LuaCall(lua_State *L, int narg, int clear); int LUACALL LuaDoFile(lua_State *L, const wxString &file); int LUACALL LuaDoBuffer(lua_State *L, const char *buffer, size_t len, const char *name); // Check the return value of LuaDoFile, LuaDoBuffer, lua_dostring, lua_dofile // returns TRUE for no error, if error fills msg with a useful message if !NULL bool wxLuaCheckRunError(int ret_val, wxString *msg); // create a reference to the object at index iParam in the Lua index int LUACALL tinsert(lua_State *luaState, int iParam); // push onto the top of the stack the object referenced by iReference bool LUACALL tget(lua_State *luaState, int iReference); // remove a Lua reference bool LUACALL tremove(lua_State *luaState, int iReference); // Get the number of items in the reference table int LUACALL tgetn(lua_State *luaState); // Display an error message void LUACALL terror(lua_State *luaState, const char *errorMsg); // push onto the top of the stack an userdata object containing u using tag to set the metatable void LUACALL tpushusertag (lua_State *L, const void *u, int tag); // get the tag of the object at index int LUACALL ttag (lua_State *L, int index); // return the user data in the userdata object at index, if reset is true clear the user data void * LUACALL ttouserdata (lua_State *L, int index, bool reset = false); // allocate a new metatable return its reference int LUACALL tnewtag(lua_State *L); int LUACALL tnewweaktag(lua_State *L, bool fWeakKey, bool fWeakData); // set the metatable of the object at top of stack from the reference tag void LUACALL tsettag(lua_State *L, int tag); // set a metamethod for the metatable referenced by tag with the supplied name and function. // if pClass is non-null set the upvalue of the function to the supplied class bool LUACALL tsettagmethod(lua_State *L, int tag, const char *method, lua_CFunction func, void *pClass = NULL); #define tpushliteralstring(L, n) \ lua_pushlstring(L, n, sizeof(n)-1) #define TLUA_NOTAG 0 class WXDLLIMPEXP_WXLUA wxLuaCheckStack { public: wxLuaCheckStack(lua_State *lua_state, const wxString &msg); ~wxLuaCheckStack(); void TestStack(const wxString &msg); static void DumpGlobals(lua_State *lua_state); static void DumpTable(lua_State *lua_state, const wxString &tableName); static void DumpTable(lua_State *lua_state, int stackIndex); private: static void DumpType(lua_State *lua_state, const wxString &name, int index, wxString &outputbuffer); static wxString GetTableInfo(lua_State *lua_state, int index); static wxString MakeNumber(double dnum); static wxString GetUserDataInfo(lua_State *lua_state, int index); lua_State *m_luastate; wxString m_msg; int m_top; }; // ---------------------------------------------------------------------------- // wxLuaFunction - a proxy class to store a reference to a Lua function. // ---------------------------------------------------------------------------- class wxLuaFunction { public: wxLuaFunction(WXLUAMETHOD *pMethod, WXLUACLASS *pClass, void *pObject) : m_pMethod(pMethod), m_pClass(pClass), m_pObject(pObject) { } ~wxLuaFunction() {} int CallMethod(lua_State *L) { lua_remove(L, 1); // remove this line to restore calling // methods using the dot notation // otherwise the colon notation *must* be used. return (*m_pMethod->func)(L); } void *GetObject() const { return m_pObject; } private: WXLUAMETHOD *m_pMethod; WXLUACLASS *m_pClass; void *m_pObject; }; // ---------------------------------------------------------------------------- // String functions - convert between Lua (ansi string) and wxString (encoded) // ---------------------------------------------------------------------------- // Convert a 8-bit Lua String into wxString inline wxString lua2wx(const char * luastr) { if (luastr == NULL) return wxEmptyString; return wxConvertMB2WX(luastr); } // Convert a wxString to 8-bit Lua String inline const wxCharBuffer wx2lua(const wxString& wxstr) { wxCharBuffer buffer(wxConvertWX2MB(wxstr.c_str())); return buffer; } // Convert a wxString to 8-bit Lua Buffer and store it class LuaCharBuffer { public: LuaCharBuffer(const wxString &wxstr) : m_buffer((const char *)NULL) { wxCharBuffer charBuffer = wxConvertWX2MB(wxstr.c_str()); m_buffer = charBuffer; } ~LuaCharBuffer() {} size_t Length() const { return strlen((const char*)m_buffer); } const char *GetData() const { return (const char*)m_buffer; } wxCharBuffer m_buffer; }; #endif // WX_LUA_INTERNALS_H |
Update of /cvsroot/wxlua/wxLua/modules/lua/src/lib In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/src/lib Added Files: Makefile README lauxlib.c lbaselib.c ldblib.c liolib.c lmathlib.c loadlib.c lstrlib.c ltablib.c Log Message: moved files to the modules directory structure --- NEW FILE: liolib.c --- /* ** $Id: liolib.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Standard I/O (and system) library ** See Copyright Notice in lua.h */ #include <errno.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define liolib_c #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** by default, gcc does not get `tmpname' */ #ifndef USE_TMPNAME #ifdef __GNUC__ #define USE_TMPNAME 0 #else #define USE_TMPNAME 1 #endif #endif /* ** by default, posix systems get `popen' */ #ifndef USE_POPEN #ifdef _POSIX_C_SOURCE #if _POSIX_C_SOURCE >= 2 #define USE_POPEN 1 #endif #endif #endif #ifndef USE_POPEN #define USE_POPEN 0 #endif /* ** {====================================================== ** FILE Operations ** ======================================================= */ #if !USE_POPEN #define pclose(f) (-1) #endif #define FILEHANDLE "FILE*" #define IO_INPUT "_input" #define IO_OUTPUT "_output" static int pushresult (lua_State *L, int i, const char *filename) { if (i) { lua_pushboolean(L, 1); return 1; } else { lua_pushnil(L); if (filename) lua_pushfstring(L, "%s: %s", filename, strerror(errno)); else lua_pushfstring(L, "%s", strerror(errno)); lua_pushnumber(L, errno); return 3; } } static FILE **topfile (lua_State *L, int findex) { FILE **f = (FILE **)luaL_checkudata(L, findex, FILEHANDLE); if (f == NULL) luaL_argerror(L, findex, "bad file"); return f; } static int io_type (lua_State *L) { FILE **f = (FILE **)luaL_checkudata(L, 1, FILEHANDLE); if (f == NULL) lua_pushnil(L); else if (*f == NULL) lua_pushliteral(L, "closed file"); else lua_pushliteral(L, "file"); return 1; } static FILE *tofile (lua_State *L, int findex) { FILE **f = topfile(L, findex); if (*f == NULL) luaL_error(L, "attempt to use a closed file"); return *f; } /* ** When creating file handles, always creates a `closed' file handle ** before opening the actual file; so, if there is a memory error, the ** file is not left opened. */ static FILE **newfile (lua_State *L) { FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *)); *pf = NULL; /* file handle is currently `closed' */ luaL_getmetatable(L, FILEHANDLE); lua_setmetatable(L, -2); return pf; } /* ** assumes that top of the stack is the `io' library, and next is ** the `io' metatable */ static void registerfile (lua_State *L, FILE *f, const char *name, const char *impname) { lua_pushstring(L, name); *newfile(L) = f; if (impname) { lua_pushstring(L, impname); lua_pushvalue(L, -2); lua_settable(L, -6); /* metatable[impname] = file */ } lua_settable(L, -3); /* io[name] = file */ } static int aux_close (lua_State *L) { FILE *f = tofile(L, 1); if (f == stdin || f == stdout || f == stderr) return 0; /* file cannot be closed */ else { int ok = (pclose(f) != -1) || (fclose(f) == 0); if (ok) *(FILE **)lua_touserdata(L, 1) = NULL; /* mark file as closed */ return ok; } } static int io_close (lua_State *L) { if (lua_isnone(L, 1) && lua_type(L, lua_upvalueindex(1)) == LUA_TTABLE) { lua_pushstring(L, IO_OUTPUT); lua_rawget(L, lua_upvalueindex(1)); } return pushresult(L, aux_close(L), NULL); } static int io_gc (lua_State *L) { FILE **f = topfile(L, 1); if (*f != NULL) /* ignore closed files */ aux_close(L); return 0; } static int io_tostring (lua_State *L) { char buff[128]; FILE **f = topfile(L, 1); if (*f == NULL) strcpy(buff, "closed"); else sprintf(buff, "%p", lua_touserdata(L, 1)); lua_pushfstring(L, "file (%s)", buff); return 1; } static int io_open (lua_State *L) { const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); FILE **pf = newfile(L); *pf = fopen(filename, mode); return (*pf == NULL) ? pushresult(L, 0, filename) : 1; } static int io_popen (lua_State *L) { #if !USE_POPEN luaL_error(L, "`popen' not supported"); return 0; #else const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); FILE **pf = newfile(L); *pf = popen(filename, mode); return (*pf == NULL) ? pushresult(L, 0, filename) : 1; #endif } static int io_tmpfile (lua_State *L) { FILE **pf = newfile(L); *pf = tmpfile(); return (*pf == NULL) ? pushresult(L, 0, NULL) : 1; } static FILE *getiofile (lua_State *L, const char *name) { lua_pushstring(L, name); lua_rawget(L, lua_upvalueindex(1)); return tofile(L, -1); } static int g_iofile (lua_State *L, const char *name, const char *mode) { if (!lua_isnoneornil(L, 1)) { const char *filename = lua_tostring(L, 1); lua_pushstring(L, name); if (filename) { FILE **pf = newfile(L); *pf = fopen(filename, mode); if (*pf == NULL) { lua_pushfstring(L, "%s: %s", filename, strerror(errno)); luaL_argerror(L, 1, lua_tostring(L, -1)); } } else { tofile(L, 1); /* check that it's a valid file handle */ lua_pushvalue(L, 1); } lua_rawset(L, lua_upvalueindex(1)); } /* return current value */ lua_pushstring(L, name); lua_rawget(L, lua_upvalueindex(1)); return 1; } static int io_input (lua_State *L) { return g_iofile(L, IO_INPUT, "r"); } static int io_output (lua_State *L) { return g_iofile(L, IO_OUTPUT, "w"); } static int io_readline (lua_State *L); static void aux_lines (lua_State *L, int idx, int close) { lua_pushliteral(L, FILEHANDLE); lua_rawget(L, LUA_REGISTRYINDEX); lua_pushvalue(L, idx); lua_pushboolean(L, close); /* close/not close file when finished */ lua_pushcclosure(L, io_readline, 3); } static int f_lines (lua_State *L) { tofile(L, 1); /* check that it's a valid file handle */ aux_lines(L, 1, 0); return 1; } static int io_lines (lua_State *L) { if (lua_isnoneornil(L, 1)) { /* no arguments? */ lua_pushstring(L, IO_INPUT); lua_rawget(L, lua_upvalueindex(1)); /* will iterate over default input */ return f_lines(L); } else { const char *filename = luaL_checkstring(L, 1); FILE **pf = newfile(L); *pf = fopen(filename, "r"); luaL_argcheck(L, *pf, 1, strerror(errno)); aux_lines(L, lua_gettop(L), 1); return 1; } } /* ** {====================================================== ** READ ** ======================================================= */ static int read_number (lua_State *L, FILE *f) { lua_Number d; if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) { lua_pushnumber(L, d); return 1; } else return 0; /* read fails */ } static int test_eof (lua_State *L, FILE *f) { int c = getc(f); ungetc(c, f); lua_pushlstring(L, NULL, 0); return (c != EOF); } static int read_line (lua_State *L, FILE *f) { luaL_Buffer b; luaL_buffinit(L, &b); for (;;) { size_t l; char *p = luaL_prepbuffer(&b); if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ luaL_pushresult(&b); /* close buffer */ return (lua_strlen(L, -1) > 0); /* check whether read something */ } l = strlen(p); if (p[l-1] != '\n') luaL_addsize(&b, l); else { luaL_addsize(&b, l - 1); /* do not include `eol' */ luaL_pushresult(&b); /* close buffer */ return 1; /* read at least an `eol' */ } } } static int read_chars (lua_State *L, FILE *f, size_t n) { size_t rlen; /* how much to read */ size_t nr; /* number of chars actually read */ luaL_Buffer b; luaL_buffinit(L, &b); rlen = LUAL_BUFFERSIZE; /* try to read that much each time */ do { char *p = luaL_prepbuffer(&b); if (rlen > n) rlen = n; /* cannot read more than asked */ nr = fread(p, sizeof(char), rlen, f); luaL_addsize(&b, nr); n -= nr; /* still have to read `n' chars */ } while (n > 0 && nr == rlen); /* until end of count or eof */ luaL_pushresult(&b); /* close buffer */ return (n == 0 || lua_strlen(L, -1) > 0); } static int g_read (lua_State *L, FILE *f, int first) { int nargs = lua_gettop(L) - 1; int success; int n; if (nargs == 0) { /* no arguments? */ success = read_line(L, f); n = first+1; /* to return 1 result */ } else { /* ensure stack space for all results and for auxlib's buffer */ luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); success = 1; for (n = first; nargs-- && success; n++) { if (lua_type(L, n) == LUA_TNUMBER) { size_t l = (size_t)lua_tonumber(L, n); success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); } else { const char *p = lua_tostring(L, n); luaL_argcheck(L, p && p[0] == '*', n, "invalid option"); switch (p[1]) { case 'n': /* number */ success = read_number(L, f); break; case 'l': /* line */ success = read_line(L, f); break; case 'a': /* file */ read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */ success = 1; /* always success */ break; case 'w': /* word */ return luaL_error(L, "obsolete option `*w' to `read'"); default: return luaL_argerror(L, n, "invalid format"); } } } } if (!success) { lua_pop(L, 1); /* remove last result */ lua_pushnil(L); /* push nil instead */ } return n - first; } static int io_read (lua_State *L) { return g_read(L, getiofile(L, IO_INPUT), 1); } static int f_read (lua_State *L) { return g_read(L, tofile(L, 1), 2); } static int io_readline (lua_State *L) { FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(2)); if (f == NULL) /* file is already closed? */ luaL_error(L, "file is already closed"); if (read_line(L, f)) return 1; else { /* EOF */ if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ lua_settop(L, 0); lua_pushvalue(L, lua_upvalueindex(2)); aux_close(L); /* close it */ } return 0; } } /* }====================================================== */ static int g_write (lua_State *L, FILE *f, int arg) { int nargs = lua_gettop(L) - 1; int status = 1; for (; nargs--; arg++) { if (lua_type(L, arg) == LUA_TNUMBER) { /* optimization: could be done exactly as for strings */ status = status && fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0; } else { size_t l; const char *s = luaL_checklstring(L, arg, &l); status = status && (fwrite(s, sizeof(char), l, f) == l); } } return pushresult(L, status, NULL); } static int io_write (lua_State *L) { return g_write(L, getiofile(L, IO_OUTPUT), 1); } static int f_write (lua_State *L) { return g_write(L, tofile(L, 1), 2); } static int f_seek (lua_State *L) { static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; static const char *const modenames[] = {"set", "cur", "end", NULL}; FILE *f = tofile(L, 1); int op = luaL_findstring(luaL_optstring(L, 2, "cur"), modenames); long offset = luaL_optlong(L, 3, 0); luaL_argcheck(L, op != -1, 2, "invalid mode"); op = fseek(f, offset, mode[op]); if (op) return pushresult(L, 0, NULL); /* error */ else { lua_pushnumber(L, ftell(f)); return 1; } } static int io_flush (lua_State *L) { return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); } static int f_flush (lua_State *L) { return pushresult(L, fflush(tofile(L, 1)) == 0, NULL); } static const luaL_reg iolib[] = { {"input", io_input}, {"output", io_output}, {"lines", io_lines}, {"close", io_close}, {"flush", io_flush}, {"open", io_open}, {"popen", io_popen}, {"read", io_read}, {"tmpfile", io_tmpfile}, {"type", io_type}, {"write", io_write}, {NULL, NULL} }; static const luaL_reg flib[] = { {"flush", f_flush}, {"read", f_read}, {"lines", f_lines}, {"seek", f_seek}, {"write", f_write}, {"close", io_close}, {"__gc", io_gc}, {"__tostring", io_tostring}, {NULL, NULL} }; static void createmeta (lua_State *L) { luaL_newmetatable(L, FILEHANDLE); /* create new metatable for file handles */ /* file methods */ lua_pushliteral(L, "__index"); lua_pushvalue(L, -2); /* push metatable */ lua_rawset(L, -3); /* metatable.__index = metatable */ luaL_openlib(L, NULL, flib, 0); } /* }====================================================== */ /* ** {====================================================== ** Other O.S. Operations ** ======================================================= */ static int io_execute (lua_State *L) { lua_pushnumber(L, system(luaL_checkstring(L, 1))); return 1; } static int io_remove (lua_State *L) { const char *filename = luaL_checkstring(L, 1); return pushresult(L, remove(filename) == 0, filename); } static int io_rename (lua_State *L) { const char *fromname = luaL_checkstring(L, 1); const char *toname = luaL_checkstring(L, 2); return pushresult(L, rename(fromname, toname) == 0, fromname); } static int io_tmpname (lua_State *L) { #if !USE_TMPNAME luaL_error(L, "`tmpname' not supported"); return 0; #else char buff[L_tmpnam]; if (tmpnam(buff) != buff) return luaL_error(L, "unable to generate a unique filename in `tmpname'"); lua_pushstring(L, buff); return 1; #endif } static int io_getenv (lua_State *L) { lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ return 1; } static int io_clock (lua_State *L) { lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); return 1; } /* ** {====================================================== ** Time/Date operations ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, ** wday=%w+1, yday=%j, isdst=? } ** ======================================================= */ static void setfield (lua_State *L, const char *key, int value) { lua_pushstring(L, key); lua_pushnumber(L, value); lua_rawset(L, -3); } static void setboolfield (lua_State *L, const char *key, int value) { lua_pushstring(L, key); lua_pushboolean(L, value); lua_rawset(L, -3); } static int getboolfield (lua_State *L, const char *key) { int res; lua_pushstring(L, key); lua_gettable(L, -2); res = lua_toboolean(L, -1); lua_pop(L, 1); return res; } static int getfield (lua_State *L, const char *key, int d) { int res; lua_pushstring(L, key); lua_gettable(L, -2); if (lua_isnumber(L, -1)) res = (int)(lua_tonumber(L, -1)); else { if (d == -2) return luaL_error(L, "field `%s' missing in date table", key); res = d; } lua_pop(L, 1); return res; } static int io_date (lua_State *L) { const char *s = luaL_optstring(L, 1, "%c"); time_t t = (time_t)(luaL_optnumber(L, 2, -1)); struct tm *stm; if (t == (time_t)(-1)) /* no time given? */ t = time(NULL); /* use current time */ if (*s == '!') { /* UTC? */ stm = gmtime(&t); s++; /* skip `!' */ } else stm = localtime(&t); if (stm == NULL) /* invalid date? */ lua_pushnil(L); else if (strcmp(s, "*t") == 0) { lua_newtable(L); setfield(L, "sec", stm->tm_sec); setfield(L, "min", stm->tm_min); setfield(L, "hour", stm->tm_hour); setfield(L, "day", stm->tm_mday); setfield(L, "month", stm->tm_mon+1); setfield(L, "year", stm->tm_year+1900); setfield(L, "wday", stm->tm_wday+1); setfield(L, "yday", stm->tm_yday+1); setboolfield(L, "isdst", stm->tm_isdst); } else { char b[256]; if (strftime(b, sizeof(b), s, stm)) lua_pushstring(L, b); else return luaL_error(L, "`date' format too long"); } return 1; } static int io_time (lua_State *L) { if (lua_isnoneornil(L, 1)) /* called without args? */ lua_pushnumber(L, time(NULL)); /* return current time */ else { time_t t; struct tm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ ts.tm_sec = getfield(L, "sec", 0); ts.tm_min = getfield(L, "min", 0); ts.tm_hour = getfield(L, "hour", 12); ts.tm_mday = getfield(L, "day", -2); ts.tm_mon = getfield(L, "month", -2) - 1; ts.tm_year = getfield(L, "year", -2) - 1900; ts.tm_isdst = getboolfield(L, "isdst"); t = mktime(&ts); if (t == (time_t)(-1)) lua_pushnil(L); else lua_pushnumber(L, t); } return 1; } static int io_difftime (lua_State *L) { lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)), (time_t)(luaL_optnumber(L, 2, 0)))); return 1; } /* }====================================================== */ static int io_setloc (lua_State *L) { static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME}; static const char *const catnames[] = {"all", "collate", "ctype", "monetary", "numeric", "time", NULL}; const char *l = lua_tostring(L, 1); int op = luaL_findstring(luaL_optstring(L, 2, "all"), catnames); luaL_argcheck(L, l || lua_isnoneornil(L, 1), 1, "string expected"); luaL_argcheck(L, op != -1, 2, "invalid option"); lua_pushstring(L, setlocale(cat[op], l)); return 1; } static int io_exit (lua_State *L) { exit(luaL_optint(L, 1, EXIT_SUCCESS)); return 0; /* to avoid warnings */ } static const luaL_reg syslib[] = { {"clock", io_clock}, {"date", io_date}, {"difftime", io_difftime}, {"execute", io_execute}, {"exit", io_exit}, {"getenv", io_getenv}, {"remove", io_remove}, {"rename", io_rename}, {"setlocale", io_setloc}, {"time", io_time}, {"tmpname", io_tmpname}, {NULL, NULL} }; /* }====================================================== */ LUALIB_API int luaopen_io (lua_State *L) { luaL_openlib(L, LUA_OSLIBNAME, syslib, 0); createmeta(L); lua_pushvalue(L, -1); luaL_openlib(L, LUA_IOLIBNAME, iolib, 1); /* put predefined file handles into `io' table */ registerfile(L, stdin, "stdin", IO_INPUT); registerfile(L, stdout, "stdout", IO_OUTPUT); registerfile(L, stderr, "stderr", NULL); return 1; } --- NEW FILE: lmathlib.c --- /* ** $Id: lmathlib.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Standard mathematical library ** See Copyright Notice in lua.h */ #include <stdlib.h> #include <math.h> #define lmathlib_c #include "lua.h" #include "lauxlib.h" #include "lualib.h" #undef PI #define PI (3.14159265358979323846) #define RADIANS_PER_DEGREE (PI/180.0) /* ** If you want Lua to operate in degrees (instead of radians), ** define USE_DEGREES */ #ifdef USE_DEGREES #define FROMRAD(a) ((a)/RADIANS_PER_DEGREE) #define TORAD(a) ((a)*RADIANS_PER_DEGREE) #else #define FROMRAD(a) (a) #define TORAD(a) (a) #endif static int math_abs (lua_State *L) { lua_pushnumber(L, fabs(luaL_checknumber(L, 1))); return 1; } static int math_sin (lua_State *L) { lua_pushnumber(L, sin(TORAD(luaL_checknumber(L, 1)))); return 1; } static int math_cos (lua_State *L) { lua_pushnumber(L, cos(TORAD(luaL_checknumber(L, 1)))); return 1; } static int math_tan (lua_State *L) { lua_pushnumber(L, tan(TORAD(luaL_checknumber(L, 1)))); return 1; } static int math_asin (lua_State *L) { lua_pushnumber(L, FROMRAD(asin(luaL_checknumber(L, 1)))); return 1; } static int math_acos (lua_State *L) { lua_pushnumber(L, FROMRAD(acos(luaL_checknumber(L, 1)))); return 1; } static int math_atan (lua_State *L) { lua_pushnumber(L, FROMRAD(atan(luaL_checknumber(L, 1)))); return 1; } static int math_atan2 (lua_State *L) { lua_pushnumber(L, FROMRAD(atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2)))); return 1; } static int math_ceil (lua_State *L) { lua_pushnumber(L, ceil(luaL_checknumber(L, 1))); return 1; } static int math_floor (lua_State *L) { lua_pushnumber(L, floor(luaL_checknumber(L, 1))); return 1; } static int math_mod (lua_State *L) { lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); return 1; } static int math_sqrt (lua_State *L) { lua_pushnumber(L, sqrt(luaL_checknumber(L, 1))); return 1; } static int math_pow (lua_State *L) { lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); return 1; } static int math_log (lua_State *L) { lua_pushnumber(L, log(luaL_checknumber(L, 1))); return 1; } static int math_log10 (lua_State *L) { lua_pushnumber(L, log10(luaL_checknumber(L, 1))); return 1; } static int math_exp (lua_State *L) { lua_pushnumber(L, exp(luaL_checknumber(L, 1))); return 1; } static int math_deg (lua_State *L) { lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE); return 1; } static int math_rad (lua_State *L) { lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE); return 1; } static int math_frexp (lua_State *L) { int e; lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e)); lua_pushnumber(L, e); return 2; } static int math_ldexp (lua_State *L) { lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), luaL_checkint(L, 2))); return 1; } static int math_min (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number dmin = luaL_checknumber(L, 1); int i; for (i=2; i<=n; i++) { lua_Number d = luaL_checknumber(L, i); if (d < dmin) dmin = d; } lua_pushnumber(L, dmin); return 1; } static int math_max (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number dmax = luaL_checknumber(L, 1); int i; for (i=2; i<=n; i++) { lua_Number d = luaL_checknumber(L, i); if (d > dmax) dmax = d; } lua_pushnumber(L, dmax); return 1; } static int math_random (lua_State *L) { /* the `%' avoids the (rare) case of r==1, and is needed also because on some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */ lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX; switch (lua_gettop(L)) { /* check number of arguments */ case 0: { /* no arguments */ lua_pushnumber(L, r); /* Number between 0 and 1 */ break; } case 1: { /* only upper limit */ int u = luaL_checkint(L, 1); luaL_argcheck(L, 1<=u, 1, "interval is empty"); lua_pushnumber(L, (int)floor(r*u)+1); /* int between 1 and `u' */ break; } case 2: { /* lower and upper limits */ int l = luaL_checkint(L, 1); int u = luaL_checkint(L, 2); luaL_argcheck(L, l<=u, 2, "interval is empty"); lua_pushnumber(L, (int)floor(r*(u-l+1))+l); /* int between `l' and `u' */ break; } default: return luaL_error(L, "wrong number of arguments"); } return 1; } static int math_randomseed (lua_State *L) { srand(luaL_checkint(L, 1)); return 0; } static const luaL_reg mathlib[] = { {"abs", math_abs}, {"sin", math_sin}, {"cos", math_cos}, {"tan", math_tan}, {"asin", math_asin}, {"acos", math_acos}, {"atan", math_atan}, {"atan2", math_atan2}, {"ceil", math_ceil}, {"floor", math_floor}, {"mod", math_mod}, {"frexp", math_frexp}, {"ldexp", math_ldexp}, {"sqrt", math_sqrt}, {"min", math_min}, {"max", math_max}, {"log", math_log}, {"log10", math_log10}, {"exp", math_exp}, {"deg", math_deg}, {"pow", math_pow}, {"rad", math_rad}, {"random", math_random}, {"randomseed", math_randomseed}, {NULL, NULL} }; /* ** Open math library */ LUALIB_API int luaopen_math (lua_State *L) { luaL_openlib(L, LUA_MATHLIBNAME, mathlib, 0); lua_pushliteral(L, "pi"); lua_pushnumber(L, PI); lua_settable(L, -3); lua_pushliteral(L, "__pow"); lua_pushcfunction(L, math_pow); lua_settable(L, LUA_GLOBALSINDEX); return 1; } --- NEW FILE: ltablib.c --- /* ** $Id: ltablib.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Library for Table Manipulation ** See Copyright Notice in lua.h */ #include <stddef.h> #define ltablib_c #include "lua.h" #include "lauxlib.h" #include "lualib.h" #define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n)) static int luaB_foreachi (lua_State *L) { int i; int n = aux_getn(L, 1); luaL_checktype(L, 2, LUA_TFUNCTION); for (i=1; i<=n; i++) { lua_pushvalue(L, 2); /* function */ lua_pushnumber(L, (lua_Number)i); /* 1st argument */ lua_rawgeti(L, 1, i); /* 2nd argument */ lua_call(L, 2, 1); if (!lua_isnil(L, -1)) return 1; lua_pop(L, 1); /* remove nil result */ } return 0; } static int luaB_foreach (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checktype(L, 2, LUA_TFUNCTION); lua_pushnil(L); /* first key */ for (;;) { if (lua_next(L, 1) == 0) return 0; lua_pushvalue(L, 2); /* function */ lua_pushvalue(L, -3); /* key */ lua_pushvalue(L, -3); /* value */ lua_call(L, 2, 1); if (!lua_isnil(L, -1)) return 1; lua_pop(L, 2); /* remove value and result */ } } static int luaB_getn (lua_State *L) { lua_pushnumber(L, (lua_Number)aux_getn(L, 1)); return 1; } static int luaB_setn (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_setn(L, 1, luaL_checkint(L, 2)); return 0; } static int luaB_tinsert (lua_State *L) { int v = lua_gettop(L); /* number of arguments */ int n = aux_getn(L, 1) + 1; int pos; /* where to insert new element */ if (v == 2) /* called with only 2 arguments */ pos = n; /* insert new element at the end */ else { pos = luaL_checkint(L, 2); /* 2nd argument is the position */ if (pos > n) n = pos; /* `grow' array if necessary */ v = 3; /* function may be called with more than 3 args */ } luaL_setn(L, 1, n); /* new size */ while (--n >= pos) { /* move up elements */ lua_rawgeti(L, 1, n); lua_rawseti(L, 1, n+1); /* t[n+1] = t[n] */ } lua_pushvalue(L, v); lua_rawseti(L, 1, pos); /* t[pos] = v */ return 0; } static int luaB_tremove (lua_State *L) { int n = aux_getn(L, 1); int pos = luaL_optint(L, 2, n); if (n <= 0) return 0; /* table is `empty' */ luaL_setn(L, 1, n-1); /* t.n = n-1 */ lua_rawgeti(L, 1, pos); /* result = t[pos] */ for ( ;pos<n; pos++) { lua_rawgeti(L, 1, pos+1); lua_rawseti(L, 1, pos); /* t[pos] = t[pos+1] */ } lua_pushnil(L); lua_rawseti(L, 1, n); /* t[n] = nil */ return 1; } static int str_concat (lua_State *L) { luaL_Buffer b; size_t lsep; const char *sep = luaL_optlstring(L, 2, "", &lsep); int i = luaL_optint(L, 3, 1); int n = luaL_optint(L, 4, 0); luaL_checktype(L, 1, LUA_TTABLE); if (n == 0) n = luaL_getn(L, 1); luaL_buffinit(L, &b); for (; i <= n; i++) { lua_rawgeti(L, 1, i); luaL_argcheck(L, lua_isstring(L, -1), 1, "table contains non-strings"); luaL_addvalue(&b); if (i != n) luaL_addlstring(&b, sep, lsep); } luaL_pushresult(&b); return 1; } /* ** {====================================================== ** Quicksort ** (based on `Algorithms in MODULA-3', Robert Sedgewick; ** Addison-Wesley, 1993.) */ static void set2 (lua_State *L, int i, int j) { lua_rawseti(L, 1, i); lua_rawseti(L, 1, j); } static int sort_comp (lua_State *L, int a, int b) { if (!lua_isnil(L, 2)) { /* function? */ int res; lua_pushvalue(L, 2); lua_pushvalue(L, a-1); /* -1 to compensate function */ lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */ lua_call(L, 2, 1); res = lua_toboolean(L, -1); lua_pop(L, 1); return res; } else /* a < b? */ return lua_lessthan(L, a, b); } static void auxsort (lua_State *L, int l, int u) { while (l < u) { /* for tail recursion */ int i, j; /* sort elements a[l], a[(l+u)/2] and a[u] */ lua_rawgeti(L, 1, l); lua_rawgeti(L, 1, u); if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */ set2(L, l, u); /* swap a[l] - a[u] */ else lua_pop(L, 2); if (u-l == 1) break; /* only 2 elements */ i = (l+u)/2; lua_rawgeti(L, 1, i); lua_rawgeti(L, 1, l); if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */ set2(L, i, l); else { lua_pop(L, 1); /* remove a[l] */ lua_rawgeti(L, 1, u); if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */ set2(L, i, u); else lua_pop(L, 2); } if (u-l == 2) break; /* only 3 elements */ lua_rawgeti(L, 1, i); /* Pivot */ lua_pushvalue(L, -1); lua_rawgeti(L, 1, u-1); set2(L, i, u-1); /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */ i = l; j = u-1; for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */ /* repeat ++i until a[i] >= P */ while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) { if (i>u) luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[i] */ } /* repeat --j until a[j] <= P */ while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) { if (j<l) luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[j] */ } if (j<i) { lua_pop(L, 3); /* pop pivot, a[i], a[j] */ break; } set2(L, i, j); } lua_rawgeti(L, 1, u-1); lua_rawgeti(L, 1, i); set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */ /* a[l..i-1] <= a[i] == P <= a[i+1..u] */ /* adjust so that smaller half is in [j..i] and larger one in [l..u] */ if (i-l < u-i) { j=l; i=i-1; l=i+2; } else { j=i+1; i=u; u=j-2; } auxsort(L, j, i); /* call recursively the smaller one */ } /* repeat the routine for the larger one */ } static int luaB_sort (lua_State *L) { int n = aux_getn(L, 1); luaL_checkstack(L, 40, ""); /* assume array is smaller than 2^40 */ if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ luaL_checktype(L, 2, LUA_TFUNCTION); lua_settop(L, 2); /* make sure there is two arguments */ auxsort(L, 1, n); return 0; } /* }====================================================== */ static const luaL_reg tab_funcs[] = { {"concat", str_concat}, {"foreach", luaB_foreach}, {"foreachi", luaB_foreachi}, {"getn", luaB_getn}, {"setn", luaB_setn}, {"sort", luaB_sort}, {"insert", luaB_tinsert}, {"remove", luaB_tremove}, {NULL, NULL} }; LUALIB_API int luaopen_table (lua_State *L) { luaL_openlib(L, LUA_TABLIBNAME, tab_funcs, 0); return 1; } --- NEW FILE: lstrlib.c --- /* ** $Id: lstrlib.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Standard library for string operations and pattern-matching ** See Copyright Notice in lua.h */ #include <ctype.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define lstrlib_c #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* macro to `unsign' a character */ #ifndef uchar #define uchar(c) ((unsigned char)(c)) #endif typedef long sint32; /* a signed version for size_t */ static int str_len (lua_State *L) { size_t l; luaL_checklstring(L, 1, &l); lua_pushnumber(L, (lua_Number)l); return 1; } static sint32 posrelat (sint32 pos, size_t len) { /* relative string position: negative means back from end */ return (pos>=0) ? pos : (sint32)len+pos+1; } static int str_sub (lua_State *L) { size_t l; const char *s = luaL_checklstring(L, 1, &l); sint32 start = posrelat(luaL_checklong(L, 2), l); sint32 end = posrelat(luaL_optlong(L, 3, -1), l); if (start < 1) start = 1; if (end > (sint32)l) end = (sint32)l; if (start <= end) lua_pushlstring(L, s+start-1, end-start+1); else lua_pushliteral(L, ""); return 1; } static int str_lower (lua_State *L) { size_t l; size_t i; luaL_Buffer b; const char *s = luaL_checklstring(L, 1, &l); luaL_buffinit(L, &b); for (i=0; i<l; i++) luaL_putchar(&b, tolower(uchar(s[i]))); luaL_pushresult(&b); return 1; } static int str_upper (lua_State *L) { size_t l; size_t i; luaL_Buffer b; const char *s = luaL_checklstring(L, 1, &l); luaL_buffinit(L, &b); for (i=0; i<l; i++) luaL_putchar(&b, toupper(uchar(s[i]))); luaL_pushresult(&b); return 1; } static int str_rep (lua_State *L) { size_t l; luaL_Buffer b; const char *s = luaL_checklstring(L, 1, &l); int n = luaL_checkint(L, 2); luaL_buffinit(L, &b); while (n-- > 0) luaL_addlstring(&b, s, l); luaL_pushresult(&b); return 1; } static int str_byte (lua_State *L) { size_t l; const char *s = luaL_checklstring(L, 1, &l); sint32 pos = posrelat(luaL_optlong(L, 2, 1), l); if (pos <= 0 || (size_t)(pos) > l) /* index out of range? */ return 0; /* no answer */ lua_pushnumber(L, uchar(s[pos-1])); return 1; } static int str_char (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; luaL_Buffer b; luaL_buffinit(L, &b); for (i=1; i<=n; i++) { int c = luaL_checkint(L, i); luaL_argcheck(L, uchar(c) == c, i, "invalid value"); luaL_putchar(&b, uchar(c)); } luaL_pushresult(&b); return 1; } static int writer (lua_State *L, const void* b, size_t size, void* B) { (void)L; luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); return 1; } static int str_dump (lua_State *L) { luaL_Buffer b; luaL_checktype(L, 1, LUA_TFUNCTION); luaL_buffinit(L,&b); if (!lua_dump(L, writer, &b)) luaL_error(L, "unable to dump given function"); luaL_pushresult(&b); return 1; } /* ** {====================================================== ** PATTERN MATCHING ** ======================================================= */ #ifndef MAX_CAPTURES #define MAX_CAPTURES 32 /* arbitrary limit */ #endif #define CAP_UNFINISHED (-1) #define CAP_POSITION (-2) typedef struct MatchState { const char *src_init; /* init of source string */ const char *src_end; /* end (`\0') of source string */ lua_State *L; int level; /* total number of captures (finished or unfinished) */ struct { const char *init; sint32 len; } capture[MAX_CAPTURES]; } MatchState; #define ESC '%' #define SPECIALS "^$*+?.([%-" static int check_capture (MatchState *ms, int l) { l -= '1'; if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED) return luaL_error(ms->L, "invalid capture index"); return l; } static int capture_to_close (MatchState *ms) { int level = ms->level; for (level--; level>=0; level--) if (ms->capture[level].len == CAP_UNFINISHED) return level; return luaL_error(ms->L, "invalid pattern capture"); } static const char *luaI_classend (MatchState *ms, const char *p) { switch (*p++) { case ESC: { if (*p == '\0') luaL_error(ms->L, "malformed pattern (ends with `%')"); return p+1; } case '[': { if (*p == '^') p++; do { /* look for a `]' */ if (*p == '\0') luaL_error(ms->L, "malformed pattern (missing `]')"); if (*(p++) == ESC && *p != '\0') p++; /* skip escapes (e.g. `%]') */ } while (*p != ']'); return p+1; } default: { return p; } } } static int match_class (int c, int cl) { int res; switch (tolower(cl)) { case 'a' : res = isalpha(c); break; case 'c' : res = iscntrl(c); break; case 'd' : res = isdigit(c); break; case 'l' : res = islower(c); break; case 'p' : res = ispunct(c); break; case 's' : res = isspace(c); break; case 'u' : res = isupper(c); break; case 'w' : res = isalnum(c); break; case 'x' : res = isxdigit(c); break; case 'z' : res = (c == 0); break; default: return (cl == c); } return (islower(cl) ? res : !res); } static int matchbracketclass (int c, const char *p, const char *ec) { int sig = 1; if (*(p+1) == '^') { sig = 0; p++; /* skip the `^' */ } while (++p < ec) { if (*p == ESC) { p++; if (match_class(c, *p)) return sig; } else if ((*(p+1) == '-') && (p+2 < ec)) { p+=2; if (uchar(*(p-2)) <= c && c <= uchar(*p)) return sig; } else if (uchar(*p) == c) return sig; } return !sig; } static int luaI_singlematch (int c, const char *p, const char *ep) { switch (*p) { case '.': return 1; /* matches any char */ case ESC: return match_class(c, *(p+1)); case '[': return matchbracketclass(c, p, ep-1); default: return (uchar(*p) == c); } } static const char *match (MatchState *ms, const char *s, const char *p); static const char *matchbalance (MatchState *ms, const char *s, const char *p) { if (*p == 0 || *(p+1) == 0) luaL_error(ms->L, "unbalanced pattern"); if (*s != *p) return NULL; else { int b = *p; int e = *(p+1); int cont = 1; while (++s < ms->src_end) { if (*s == e) { if (--cont == 0) return s+1; } else if (*s == b) cont++; } } return NULL; /* string ends out of balance */ } static const char *max_expand (MatchState *ms, const char *s, const char *p, const char *ep) { sint32 i = 0; /* counts maximum expand for item */ while ((s+i)<ms->src_end && luaI_singlematch(uchar(*(s+i)), p, ep)) i++; /* keeps trying to match with the maximum repetitions */ while (i>=0) { const char *res = match(ms, (s+i), ep+1); if (res) return res; i--; /* else didn't match; reduce 1 repetition to try again */ } return NULL; } static const char *min_expand (MatchState *ms, const char *s, const char *p, const char *ep) { for (;;) { const char *res = match(ms, s, ep+1); if (res != NULL) return res; else if (s<ms->src_end && luaI_singlematch(uchar(*s), p, ep)) s++; /* try with one more repetition */ else return NULL; } } static const char *start_capture (MatchState *ms, const char *s, const char *p, int what) { const char *res; int level = ms->level; if (level >= MAX_CAPTURES) luaL_error(ms->L, "too many captures"); ms->capture[level].init = s; ms->capture[level].len = what; ms->level = level+1; if ((res=match(ms, s, p)) == NULL) /* match failed? */ ms->level--; /* undo capture */ return res; } static const char *end_capture (MatchState *ms, const char *s, const char *p) { int l = capture_to_close(ms); const char *res; ms->capture[l].len = s - ms->capture[l].init; /* close capture */ if ((res = match(ms, s, p)) == NULL) /* match failed? */ ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ return res; } static const char *match_capture (MatchState *ms, const char *s, int l) { size_t len; l = check_capture(ms, l); len = ms->capture[l].len; if ((size_t)(ms->src_end-s) >= len && memcmp(ms->capture[l].init, s, len) == 0) return s+len; else return NULL; } static const char *match (MatchState *ms, const char *s, const char *p) { init: /* using goto's to optimize tail recursion */ switch (*p) { case '(': { /* start capture */ if (*(p+1) == ')') /* position capture? */ return start_capture(ms, s, p+2, CAP_POSITION); else return start_capture(ms, s, p+1, CAP_UNFINISHED); } case ')': { /* end capture */ return end_capture(ms, s, p+1); } case ESC: { switch (*(p+1)) { case 'b': { /* balanced string? */ s = matchbalance(ms, s, p+2); if (s == NULL) return NULL; p+=4; goto init; /* else return match(ms, s, p+4); */ } case 'f': { /* frontier? */ const char *ep; char previous; p += 2; if (*p != '[') luaL_error(ms->L, "missing `[' after `%%f' in pattern"); ep = luaI_classend(ms, p); /* points to what is next */ previous = (char)((s == ms->src_init) ? '\0' : *(s-1)); if (matchbracketclass(uchar(previous), p, ep-1) || !matchbracketclass(uchar(*s), p, ep-1)) return NULL; p=ep; goto init; /* else return match(ms, s, ep); */ } default: { if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */ s = match_capture(ms, s, *(p+1)); if (s == NULL) return NULL; p+=2; goto init; /* else return match(ms, s, p+2) */ } goto dflt; /* case default */ } } } case '\0': { /* end of pattern */ return s; /* match succeeded */ } case '$': { if (*(p+1) == '\0') /* is the `$' the last char in pattern? */ return (s == ms->src_end) ? s : NULL; /* check end of string */ else goto dflt; } default: dflt: { /* it is a pattern item */ const char *ep = luaI_classend(ms, p); /* points to what is next */ int m = s<ms->src_end && luaI_singlematch(uchar(*s), p, ep); switch (*ep) { case '?': { /* optional */ const char *res; if (m && ((res=match(ms, s+1, ep+1)) != NULL)) return res; p=ep+1; goto init; /* else return match(ms, s, ep+1); */ } case '*': { /* 0 or more repetitions */ return max_expand(ms, s, p, ep); } case '+': { /* 1 or more repetitions */ return (m ? max_expand(ms, s+1, p, ep) : NULL); } case '-': { /* 0 or more repetitions (minimum) */ return min_expand(ms, s, p, ep); } default: { if (!m) return NULL; s++; p=ep; goto init; /* else return match(ms, s+1, ep); */ } } } } } static const char *lmemfind (const char *s1, size_t l1, const char *s2, size_t l2) { if (l2 == 0) return s1; /* empty strings are everywhere */ else if (l2 > l1) return NULL; /* avoids a negative `l1' */ else { const char *init; /* to search for a `*s2' inside `s1' */ l2--; /* 1st char will be checked by `memchr' */ l1 = l1-l2; /* `s2' cannot be found after that */ while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { init++; /* 1st char is already checked */ if (memcmp(init, s2+1, l2) == 0) return init-1; else { /* correct `l1' and `s1' to try again */ l1 -= init-s1; s1 = init; } } return NULL; /* not found */ } } static void push_onecapture (MatchState *ms, int i) { int l = ms->capture[i].len; if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); if (l == CAP_POSITION) lua_pushnumber(ms->L, (lua_Number)(ms->capture[i].init - ms->src_init + 1)); else lua_pushlstring(ms->L, ms->capture[i].init, l); } static int push_captures (MatchState *ms, const char *s, const char *e) { int i; luaL_checkstack(ms->L, ms->level, "too many captures"); if (ms->level == 0 && s) { /* no explicit captures? */ lua_pushlstring(ms->L, s, e-s); /* return whole match */ return 1; } else { /* return all captures */ for (i=0; i<ms->level; i++) push_onecapture(ms, i); return ms->level; /* number of strings pushed */ } } static int str_find (lua_State *L) { size_t l1, l2; const char *s = luaL_checklstring(L, 1, &l1); const char *p = luaL_checklstring(L, 2, &l2); sint32 init = posrelat(luaL_optlong(L, 3, 1), l1) - 1; if (init < 0) init = 0; else if ((size_t)(init) > l1) init = (sint32)l1; if (lua_toboolean(L, 4) || /* explicit request? */ strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */ /* do a plain search */ const char *s2 = lmemfind(s+init, l1-init, p, l2); if (s2) { lua_pushnumber(L, (lua_Number)(s2-s+1)); lua_pushnumber(L, (lua_Number)(s2-s+l2)); return 2; } } else { MatchState ms; int anchor = (*p == '^') ? (p++, 1) : 0; const char *s1=s+init; ms.L = L; ms.src_init = s; ms.src_end = s+l1; do { const char *res; ms.level = 0; if ((res=match(&ms, s1, p)) != NULL) { lua_pushnumber(L, (lua_Number)(s1-s+1)); /* start */ lua_pushnumber(L, (lua_Number)(res-s)); /* end */ return push_captures(&ms, NULL, 0) + 2; } } while (s1++<ms.src_end && !anchor); } lua_pushnil(L); /* not found */ return 1; } static int gfind_aux (lua_State *L) { MatchState ms; const char *s = lua_tostring(L, lua_upvalueindex(1)); size_t ls = lua_strlen(L, lua_upvalueindex(1)); const char *p = lua_tostring(L, lua_upvalueindex(2)); const char *src; ms.L = L; ms.src_init = s; ms.src_end = s+ls; for (src = s + (size_t)lua_tonumber(L, lua_upvalueindex(3)); src <= ms.src_end; src++) { const char *e; ms.level = 0; if ((e = match(&ms, src, p)) != NULL) { int newstart = e-s; if (e == src) newstart++; /* empty match? go at least one position */ lua_pushnumber(L, (lua_Number)newstart); lua_replace(L, lua_upvalueindex(3)); return push_captures(&ms, src, e); } } return 0; /* not found */ } static int gfind (lua_State *L) { luaL_checkstring(L, 1); luaL_checkstring(L, 2); lua_settop(L, 2); lua_pushnumber(L, 0); lua_pushcclosure(L, gfind_aux, 3); return 1; } static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, const char *e) { lua_State *L = ms->L; if (lua_isstring(L, 3)) { const char *news = lua_tostring(L, 3); size_t l = lua_strlen(L, 3); size_t i; for (i=0; i<l; i++) { if (news[i] != ESC) luaL_putchar(b, news[i]); else { i++; /* skip ESC */ if (!isdigit(uchar(news[i]))) luaL_putchar(b, news[i]); else { int level = check_capture(ms, news[i]); push_onecapture(ms, level); luaL_addvalue(b); /* add capture to accumulated result */ } } } } else { /* is a function */ int n; lua_pushvalue(L, 3); n = push_captures(ms, s, e); lua_call(L, n, 1); if (lua_isstring(L, -1)) luaL_addvalue(b); /* add return to accumulated result */ else lua_pop(L, 1); /* function result is not a string: pop it */ } } static int str_gsub (lua_State *L) { size_t srcl; const char *src = luaL_checklstring(L, 1, &srcl); const char *p = luaL_checkstring(L, 2); int max_s = luaL_optint(L, 4, srcl+1); int anchor = (*p == '^') ? (p++, 1) : 0; int n = 0; MatchState ms; luaL_Buffer b; luaL_argcheck(L, lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)), 3, "string or function expected"); luaL_buffinit(L, &b); ms.L = L; ms.src_init = src; ms.src_end = src+srcl; while (n < max_s) { const char *e; ms.level = 0; e = match(&ms, src, p); if (e) { n++; add_s(&ms, &b, src, e); } if (e && e>src) /* non empty match? */ src = e; /* skip it */ else if (src < ms.src_end) luaL_putchar(&b, *src++); else break; if (anchor) break; } luaL_addlstring(&b, src, ms.src_end-src); luaL_pushresult(&b); lua_pushnumber(L, (lua_Number)n); /* number of substitutions */ return 2; } /* }====================================================== */ /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ #define MAX_ITEM 512 /* maximum size of each format specification (such as '%-099.99d') */ #define MAX_FORMAT 20 static void luaI_addquoted (lua_State *L, luaL_Buffer *b, int arg) { size_t l; const char *s = luaL_checklstring(L, arg, &l); luaL_putchar(b, '"'); while (l--) { switch (*s) { case '"': case '\\': case '\n': { luaL_putchar(b, '\\'); luaL_putchar(b, *s); break; } case '\0': { luaL_addlstring(b, "\\000", 4); break; } default: { luaL_putchar(b, *s); break; } } s++; } luaL_putchar(b, '"'); } static const char *scanformat (lua_State *L, const char *strfrmt, char *form, int *hasprecision) { const char *p = strfrmt; while (strchr("-+ #0", *p)) p++; /* skip flags */ if (isdigit(uchar(*p))) p++; /* skip width */ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ if (*p == '.') { p++; *hasprecision = 1; if (isdigit(uchar(*p))) p++; /* skip precision */ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ } if (isdigit(uchar(*p))) luaL_error(L, "invalid format (width or precision too long)"); if (p-strfrmt+2 > MAX_FORMAT) /* +2 to include `%' and the specifier */ luaL_error(L, "invalid format (too long)"); form[0] = '%'; strncpy(form+1, strfrmt, p-strfrmt+1); form[p-strfrmt+2] = 0; return p; } static int str_format (lua_State *L) { int arg = 1; size_t sfl; const char *strfrmt = luaL_checklstring(L, arg, &sfl); const char *strfrmt_end = strfrmt+sfl; luaL_Buffer b; luaL_buffinit(L, &b); while (strfrmt < strfrmt_end) { if (*strfrmt != '%') luaL_putchar(&b, *strfrmt++); else if (*++strfrmt == '%') luaL_putchar(&b, *strfrmt++); /* %% */ else { /* format item */ char form[MAX_FORMAT]; /* to store the format (`%...') */ char buff[MAX_ITEM]; /* to store the formatted item */ int hasprecision = 0; if (isdigit(uchar(*strfrmt)) && *(strfrmt+1) == '$') return luaL_error(L, "obsolete option (d$) to `format'"); arg++; strfrmt = scanformat(L, strfrmt, form, &hasprecision); switch (*strfrmt++) { case 'c': case 'd': case 'i': { sprintf(buff, form, luaL_checkint(L, arg)); break; } case 'o': case 'u': case 'x': case 'X': { sprintf(buff, form, (unsigned int)(luaL_checknumber(L, arg))); break; } case 'e': case 'E': case 'f': case 'g': case 'G': { sprintf(buff, form, luaL_checknumber(L, arg)); break; } case 'q': { luaI_addquoted(L, &b, arg); continue; /* skip the `addsize' at the end */ } case 's': { size_t l; const char *s = luaL_checklstring(L, arg, &l); if (!hasprecision && l >= 100) { /* no precision and string is too long to be formatted; keep original string */ lua_pushvalue(L, arg); luaL_addvalue(&b); continue; /* skip the `addsize' at the end */ } else { sprintf(buff, form, s); break; } } default: { /* also treat cases `pnLlh' */ return luaL_error(L, "invalid option to `format'"); } } luaL_addlstring(&b, buff, strlen(buff)); } } luaL_pushresult(&b); return 1; } static const luaL_reg strlib[] = { {"len", str_len}, {"sub", str_sub}, {"lower", str_lower}, {"upper", str_upper}, {"char", str_char}, {"rep", str_rep}, {"byte", str_byte}, {"format", str_format}, {"dump", str_dump}, {"find", str_find}, {"gfind", gfind}, {"gsub", str_gsub}, {NULL, NULL} }; /* ** Open string library */ LUALIB_API int luaopen_string (lua_State *L) { luaL_openlib(L, LUA_STRLIBNAME, strlib, 0); return 1; } --- NEW FILE: lauxlib.c --- /* ** $Id: lauxlib.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ #include <ctype.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <string.h> /* This file uses only the official API of Lua. ** Any function declared here could be written as an application function. */ #define lauxlib_c #include "lua.h" #include "lauxlib.h" /* number of prereserved references (for internal use) */ #define RESERVED_REFS 2 /* reserved references */ #define FREELIST_REF 1 /* free list of references */ #define ARRAYSIZE_REF 2 /* array sizes */ /* convert a stack index to positive */ #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \ lua_gettop(L) + (i) + 1) /* ** {====================================================== ** Error-report functions ** ======================================================= */ LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { lua_Debug ar; lua_getstack(L, 0, &ar); lua_getinfo(L, "n", &ar); if (strcmp(ar.namewhat, "method") == 0) { narg--; /* do not count `self' */ if (narg == 0) /* error is in the self argument itself? */ return luaL_error(L, "calling `%s' on bad self (%s)", ar.name, extramsg); } if (ar.name == NULL) ar.name = "?"; return luaL_error(L, "bad argument #%d to `%s' (%s)", narg, ar.name, extramsg); } LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) { const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, lua_typename(L, lua_type(L,narg))); return luaL_argerror(L, narg, msg); } static void tag_error (lua_State *L, int narg, int tag) { luaL_typerror(L, narg, lua_typename(L, tag)); } LUALIB_API void luaL_where (lua_State *L, int level) { lua_Debug ar; if (lua_getstack(L, level, &ar)) { /* check function at level */ lua_getinfo(L, "Snl", &ar); /* get info about it */ if (ar.currentline > 0) { /* is there info? */ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); return; } } lua_pushliteral(L, ""); /* else, no information available... */ } LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { va_list argp; va_start(argp, fmt); luaL_where(L, 1); lua_pushvfstring(L, fmt, argp); va_end(argp); lua_concat(L, 2); return lua_error(L); } /* }====================================================== */ LUALIB_API int luaL_findstring (const char *name, const char *const list[]) { int i; for (i=0; list[i]; i++) if (strcmp(list[i], name) == 0) return i; return -1; /* name not found */ } LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { lua_pushstring(L, tname); lua_rawget(L, LUA_REGISTRYINDEX); /* get registry.name */ if (!lua_isnil(L, -1)) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ lua_pop(L, 1); lua_newtable(L); /* create metatable */ lua_pushstring(L, tname); lua_pushvalue(L, -2); lua_rawset(L, LUA_REGISTRYINDEX); /* registry.name = metatable */ lua_pushvalue(L, -1); lua_pushstring(L, tname); lua_rawset(L, LUA_REGISTRYINDEX); /* registry[metatable] = name */ return 1; } LUALIB_API void luaL_getmetatable (lua_State *L, const char *tname) { lua_pushstring(L, tname); lua_rawget(L, LUA_REGISTRYINDEX); } LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { const char *tn; if (!lua_getmetatable(L, ud)) return NULL; /* no metatable? */ lua_rawget(L, LUA_REGISTRYINDEX); /* get registry[metatable] */ tn = lua_tostring(L, -1); if (tn && (strcmp(tn, tname) == 0)) { lua_pop(L, 1); return lua_touserdata(L, ud); } else { lua_pop(L, 1); return NULL; } } LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) { if (!lua_checkstack(L, space)) luaL_error(L, "stack overflow (%s)", mes); } LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { if (lua_type(L, narg) != t) tag_error(L, narg, t); } LUALIB_API void luaL_checkany (lua_State *L, int narg) { if (lua_type(L, narg) == LUA_TNONE) luaL_argerror(L, narg, "value expected"); } LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) { const char *s = lua_tostring(L, narg); if (!s) tag_error(L, narg, LUA_TSTRING); if (len) *len = lua_strlen(L, narg); return s; } LUALIB_API const char *luaL_optlstring (lua_State *L, int narg, const char *def, size_t *len) { if (lua_isnoneornil(L, narg)) { if (len) *len = (def ? strlen(def) : 0); return def; } else return luaL_checklstring(L, narg, len); } LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) { lua_Number d = lua_tonumber(L, narg); if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */ tag_error(L, narg, LUA_TNUMBER); return d; } LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) { if (lua_isnoneornil(L, narg)) return def; else return luaL_checknumber(L, narg); } LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { if (!lua_getmetatable(L, obj)) /* no metatable? */ return 0; lua_pushstring(L, event); lua_rawget(L, -2); if (lua_isnil(L, -1)) { lua_pop(L, 2); /* remove metatable and metafield */ return 0; } else { lua_remove(L, -2); /* remove only metatable */ return 1; } } LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { obj = abs_index(L, obj); if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ return 0; lua_pushvalue(L, obj); lua_call(L, 1, 1); return 1; } LUALIB_API void luaL_openlib (lua_State *L, const char *libname, const luaL_reg *l, int nup) { if (libname) { lua_pushstring(L, libname); lua_gettable(L, LUA_GLOBALSINDEX); /* check whether lib already exists */ if (lua_isnil(L, -1)) { /* no? */ lua_pop(L, 1); lua_newtable(L); /* create it */ lua_pushstring(L, libname); lua_pushvalue(L, -2); lua_settable(L, LUA_GLOBALSINDEX); /* register it with given name */ } lua_insert(L, -(nup+1)); /* move library table to below upvalues */ } for (; l->name; l++) { int i; lua_pushstring(L, l->name); for (i=0; i<nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -(nup+1)); lua_pushcclosure(L, l->func, nup); lua_settable(L, -(nup+3)); } lua_pop(L, nup); /* remove upvalues */ } /* ** {====================================================== ** getn-setn: size for arrays ** ======================================================= */ static int checkint (lua_State *L, int topop) { int n = (int)lua_tonumber(L, -1); if (n == 0 && !lua_isnumber(L, -1)) n = -1; lua_pop(L, topop); return n; } static void getsizes (lua_State *L) { lua_rawgeti(L, LUA_REGISTRYINDEX, ARRAYSIZE_REF); if (lua_isnil(L, -1)) { /* no `size' table? */ lua_pop(L, 1); /* remove nil */ lua_newtable(L); /* create it */ lua_pushvalue(L, -1); /* `size' will be its own metatable */ lua_setmetatable(L, -2); lua_pushliteral(L, "__mode"); lua_pushliteral(L, "k"); lua_rawset(L, -3); /* metatable(N).__mode = "k" */ lua_pushvalue(L, -1); lua_rawseti(L, LUA_REGISTRYINDEX, ARRAYSIZE_REF); /* store in register */ } } void luaL_setn (lua_State *L, int t, int n) { t = abs_index(L, t); lua_pushliteral(L, "n"); lua_rawget(L, t); if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */ lua_pushliteral(L, "n"); /* use it */ lua_pushnumber(L, (lua_Number)n); lua_rawset(L, t); } else { /* use `sizes' */ getsizes(L); lua_pushvalue(L, t); lua_pushnumber(L, (lua_Number)n); lua_rawset(L, -3); /* sizes[t] = n */ lua_pop(L, 1); /* remove `sizes' */ } } int luaL_getn (lua_State *L, int t) { int n; t = abs_index(L, t); lua_pushliteral(L, "n"); /* try t.n */ lua_rawget(L, t); if ((n = checkint(L, 1)) >= 0) return n; getsizes(L); /* else try sizes[t] */ lua_pushvalue(L, t); lua_rawget(L, -2); if ((n = checkint(L, 2)) >= 0) return n; for (n = 1; ; n++) { /* else must count elements */ lua_rawgeti(L, t, n); if (lua_isnil(L, -1)) break; lua_pop(L, 1); } lua_pop(L, 1); return n - 1; } /* }====================================================== */ /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ #define bufflen(B) ((B)->p - (B)->buffer) #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B))) #define LIMIT (LUA_MINSTACK/2) static int emptybuffer (luaL_Buffer *B) { size_t l = bufflen(B); if (l == 0) return 0; /* put nothing on stack */ else { lua_pushlstring(B->L, B->buffer, l); B->p = B->buffer; B->lvl++; return 1; } } static void adjuststack (luaL_Buffer *B) { if (B->lvl > 1) { lua_State *L = B->L; int toget = 1; /* number of levels to concat */ size_t toplen = lua_strlen(L, -1); do { size_t l = lua_strlen(L, -(toget+1)); if (B->lvl... [truncated message content] |
Update of /cvsroot/wxlua/wxLua/modules/lua/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/src Added Files: Makefile README lapi.c lapi.h lcode.c lcode.h ldebug.c ldebug.h ldllmain.c ldo.c ldo.h ldump.c lfunc.c lfunc.h lgc.c lgc.h llex.c llex.h llimits.h lmem.c lmem.h lobject.c lobject.h lopcodes.c lopcodes.h lparser.c lparser.h lstate.c lstate.h lstring.c lstring.h ltable.c ltable.h ltests.c ltm.c ltm.h luadll.rc lundump.c lundump.h lvm.c lvm.h lzio.c lzio.h makefile.b32 Log Message: moved files to the modules directory structure --- NEW FILE: ltm.c --- /* ** $Id: ltm.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Tag methods ** See Copyright Notice in lua.h */ #include <string.h> #define ltm_c #include "lua.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" const char *const luaT_typenames[] = { "nil", "boolean", "userdata", "number", "string", "table", "function", "userdata", "thread" }; void luaT_init (lua_State *L) { static const char *const luaT_eventname[] = { /* ORDER TM */ "__index", "__newindex", "__gc", "__mode", "__eq", "__add", "__sub", "__mul", "__div", "__pow", "__unm", "__lt", "__le", "__concat", "__call" }; int i; for (i=0; i<TM_N; i++) { G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]); luaS_fix(G(L)->tmname[i]); /* never collect these names */ } } /* ** function to be used with macro "fasttm": optimized for absence of ** tag methods */ const TObject *luaT_gettm (Table *events, TMS event, TString *ename) { const TObject *tm = luaH_getstr(events, ename); lua_assert(event <= TM_EQ); if (ttisnil(tm)) { /* no tag method? */ events->flags |= cast(lu_byte, 1u<<event); /* cache this fact */ return NULL; } else return tm; } const TObject *luaT_gettmbyobj (lua_State *L, const TObject *o, TMS event) { TString *ename = G(L)->tmname[event]; switch (ttype(o)) { case LUA_TTABLE: return luaH_getstr(hvalue(o)->metatable, ename); case LUA_TUSERDATA: return luaH_getstr(uvalue(o)->uv.metatable, ename); default: return &luaO_nilobject; } } --- NEW FILE: lmem.c --- /* ** $Id: lmem.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Interface to Memory Manager ** See Copyright Notice in lua.h */ #include <stdlib.h> #define lmem_c #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" /* ** definition for realloc function. It must assure that l_realloc(NULL, ** 0, x) allocates a new block (ANSI C assures that). (`os' is the old ** block size; some allocators may use that.) */ #ifndef l_realloc #define l_realloc(b,os,s) realloc(b,s) #endif /* ** definition for free function. (`os' is the old block size; some ** allocators may use that.) */ #ifndef l_free #define l_free(b,os) free(b) #endif #define MINSIZEARRAY 4 void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems, int limit, const char *errormsg) { void *newblock; int newsize = (*size)*2; if (newsize < MINSIZEARRAY) newsize = MINSIZEARRAY; /* minimum size */ else if (*size >= limit/2) { /* cannot double it? */ if (*size < limit - MINSIZEARRAY) /* try something smaller... */ newsize = limit; /* still have at least MINSIZEARRAY free places */ else luaG_runerror(L, errormsg); } newblock = luaM_realloc(L, block, cast(lu_mem, *size)*cast(lu_mem, size_elems), cast(lu_mem, newsize)*cast(lu_mem, size_elems)); *size = newsize; /* update only when everything else is OK */ return newblock; } /* ** generic allocation routine. */ void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem size) { lua_assert((oldsize == 0) == (block == NULL)); if (size == 0) { if (block != NULL) { l_free(block, oldsize); block = NULL; } else return NULL; /* avoid `nblocks' computations when oldsize==size==0 */ } else if (size >= MAX_SIZET) luaG_runerror(L, "memory allocation error: block too big"); else { block = l_realloc(block, oldsize, size); if (block == NULL) { if (L) luaD_throw(L, LUA_ERRMEM); else return NULL; /* error before creating state! */ } } if (L) { lua_assert(G(L) != NULL && G(L)->nblocks > 0); G(L)->nblocks -= oldsize; G(L)->nblocks += size; } return block; } --- NEW FILE: Makefile --- # makefile for Lua core library LUA= .. include $(LUA)/config OBJS= \ lapi.o \ lcode.o \ ldebug.o \ ldo.o \ ldump.o \ lfunc.o \ lgc.o \ llex.o \ lmem.o \ lobject.o \ lopcodes.o \ lparser.o \ lstate.o \ lstring.o \ ltable.o \ ltests.o \ ltm.o \ lundump.o \ lvm.o \ lzio.o SRCS= \ lapi.c \ lcode.c \ ldebug.c \ ldo.c \ ldump.c \ lfunc.c \ lgc.c \ llex.c \ lmem.c \ lobject.c \ lopcodes.c \ lparser.c \ lstate.c \ lstring.c \ ltable.c \ ltests.c \ ltm.c \ lundump.c \ lvm.c \ lzio.c \ lapi.h \ lcode.h \ ldebug.h \ ldo.h \ lfunc.h \ lgc.h \ llex.h \ llimits.h \ lmem.h \ lobject.h \ lopcodes.h \ lparser.h \ lstate.h \ lstring.h \ ltable.h \ ltm.h \ lundump.h \ lvm.h \ lzio.h T= $(LIB)/liblua.a all: $T $T: $(OBJS) $(AR) $@ $(OBJS) $(RANLIB) $@ clean: rm -f $(OBJS) $T co: co -q -f -M $(SRCS) klean: clean rm -f $(SRCS) --- NEW FILE: lmem.h --- /* ** $Id: lmem.h,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Interface to Memory Manager ** See Copyright Notice in lua.h */ #ifndef lmem_h #define lmem_h #include <stddef.h> #include "llimits.h" #include "lua.h" #define MEMERRMSG "not enough memory" void *luaM_realloc (lua_State *L, void *oldblock, lu_mem oldsize, lu_mem size); void *luaM_growaux (lua_State *L, void *block, int *size, int size_elem, int limit, const char *errormsg); #define luaM_free(L, b, s) luaM_realloc(L, (b), (s), 0) #define luaM_freelem(L, b) luaM_realloc(L, (b), sizeof(*(b)), 0) #define luaM_freearray(L, b, n, t) luaM_realloc(L, (b), \ cast(lu_mem, n)*cast(lu_mem, sizeof(t)), 0) #define luaM_malloc(L, t) luaM_realloc(L, NULL, 0, (t)) #define luaM_new(L, t) cast(t *, luaM_malloc(L, sizeof(t))) #define luaM_newvector(L, n,t) cast(t *, luaM_malloc(L, \ cast(lu_mem, n)*cast(lu_mem, sizeof(t)))) #define luaM_growvector(L,v,nelems,size,t,limit,e) \ if (((nelems)+1) > (size)) \ ((v)=cast(t *, luaM_growaux(L,v,&(size),sizeof(t),limit,e))) #define luaM_reallocvector(L, v,oldn,n,t) \ ((v)=cast(t *, luaM_realloc(L, v,cast(lu_mem, oldn)*cast(lu_mem, sizeof(t)), \ cast(lu_mem, n)*cast(lu_mem, sizeof(t))))) #endif --- NEW FILE: ldump.c --- /* ** $Id: ldump.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** save bytecodes ** See Copyright Notice in lua.h */ #include <stddef.h> #define ldump_c #include "lua.h" #include "lobject.h" #include "lopcodes.h" #include "lstate.h" #include "lundump.h" #define DumpVector(b,n,size,D) DumpBlock(b,(n)*(size),D) #define DumpLiteral(s,D) DumpBlock("" s,(sizeof(s))-1,D) typedef struct { lua_State* L; lua_Chunkwriter write; void* data; } DumpState; static void DumpBlock(const void* b, size_t size, DumpState* D) { lua_unlock(D->L); (*D->write)(D->L,b,size,D->data); lua_lock(D->L); } static void DumpByte(int y, DumpState* D) { char x=(char)y; DumpBlock(&x,sizeof(x),D); } static void DumpInt(int x, DumpState* D) { DumpBlock(&x,sizeof(x),D); } static void DumpSize(size_t x, DumpState* D) { DumpBlock(&x,sizeof(x),D); } static void DumpNumber(lua_Number x, DumpState* D) { DumpBlock(&x,sizeof(x),D); } static void DumpString(TString* s, DumpState* D) { if (s==NULL || getstr(s)==NULL) DumpSize(0,D); else { size_t size=s->tsv.len+1; /* include trailing '\0' */ DumpSize(size,D); DumpBlock(getstr(s),size,D); } } static void DumpCode(const Proto* f, DumpState* D) { DumpInt(f->sizecode,D); DumpVector(f->code,f->sizecode,sizeof(*f->code),D); } static void DumpLocals(const Proto* f, DumpState* D) { int i,n=f->sizelocvars; DumpInt(n,D); for (i=0; i<n; i++) { DumpString(f->locvars[i].varname,D); DumpInt(f->locvars[i].startpc,D); DumpInt(f->locvars[i].endpc,D); } } static void DumpLines(const Proto* f, DumpState* D) { DumpInt(f->sizelineinfo,D); DumpVector(f->lineinfo,f->sizelineinfo,sizeof(*f->lineinfo),D); } static void DumpUpvalues(const Proto* f, DumpState* D) { int i,n=f->sizeupvalues; DumpInt(n,D); for (i=0; i<n; i++) DumpString(f->upvalues[i],D); } static void DumpFunction(const Proto* f, const TString* p, DumpState* D); static void DumpConstants(const Proto* f, DumpState* D) { int i,n; DumpInt(n=f->sizek,D); for (i=0; i<n; i++) { const TObject* o=&f->k[i]; DumpByte(ttype(o),D); switch (ttype(o)) { case LUA_TNUMBER: DumpNumber(nvalue(o),D); break; case LUA_TSTRING: DumpString(tsvalue(o),D); break; case LUA_TNIL: break; default: lua_assert(0); /* cannot happen */ break; } } DumpInt(n=f->sizep,D); for (i=0; i<n; i++) DumpFunction(f->p[i],f->source,D); } static void DumpFunction(const Proto* f, const TString* p, DumpState* D) { DumpString((f->source==p) ? NULL : f->source,D); DumpInt(f->lineDefined,D); DumpByte(f->nups,D); DumpByte(f->numparams,D); DumpByte(f->is_vararg,D); DumpByte(f->maxstacksize,D); DumpLines(f,D); DumpLocals(f,D); DumpUpvalues(f,D); DumpConstants(f,D); DumpCode(f,D); } static void DumpHeader(DumpState* D) { DumpLiteral(LUA_SIGNATURE,D); DumpByte(VERSION,D); DumpByte(luaU_endianness(),D); DumpByte(sizeof(int),D); DumpByte(sizeof(size_t),D); DumpByte(sizeof(Instruction),D); DumpByte(SIZE_OP,D); DumpByte(SIZE_A,D); DumpByte(SIZE_B,D); DumpByte(SIZE_C,D); DumpByte(sizeof(lua_Number),D); DumpNumber(TEST_NUMBER,D); } /* ** dump function as precompiled chunk */ void luaU_dump (lua_State* L, const Proto* Main, lua_Chunkwriter w, void* data) { DumpState D; D.L=L; D.write=w; D.data=data; DumpHeader(&D); DumpFunction(Main,NULL,&D); } --- NEW FILE: ltable.h --- /* ** $Id: ltable.h,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ #ifndef ltable_h #define ltable_h #include "lobject.h" #define gnode(t,i) (&(t)->node[i]) #define gkey(n) (&(n)->i_key) #define gval(n) (&(n)->i_val) const TObject *luaH_getnum (Table *t, int key); TObject *luaH_setnum (lua_State *L, Table *t, int key); const TObject *luaH_getstr (Table *t, TString *key); const TObject *luaH_get (Table *t, const TObject *key); TObject *luaH_set (lua_State *L, Table *t, const TObject *key); Table *luaH_new (lua_State *L, int narray, int lnhash); void luaH_free (lua_State *L, Table *t); int luaH_next (lua_State *L, Table *t, StkId key); /* exported only for debugging */ Node *luaH_mainposition (const Table *t, const TObject *key); #endif --- NEW FILE: ldebug.h --- /* ** $Id: ldebug.h,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Auxiliary functions from Debug Interface module ** See Copyright Notice in lua.h */ #ifndef ldebug_h #define ldebug_h #include "lstate.h" #define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) #define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0) #define resethookcount(L) (L->hookcount = L->basehookcount) void luaG_inithooks (lua_State *L); void luaG_typeerror (lua_State *L, const TObject *o, const char *opname); void luaG_concaterror (lua_State *L, StkId p1, StkId p2); void luaG_aritherror (lua_State *L, const TObject *p1, const TObject *p2); int luaG_ordererror (lua_State *L, const TObject *p1, const TObject *p2); void luaG_runerror (lua_State *L, const char *fmt, ...); void luaG_errormsg (lua_State *L); int luaG_checkcode (const Proto *pt); #endif --- NEW FILE: ltable.c --- /* ** $Id: ltable.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ /* ** Implementation of tables (aka arrays, objects, or hash tables). ** Tables keep its elements in two parts: an array part and a hash part. ** Non-negative integer keys are all candidates to be kept in the array ** part. The actual size of the array is the largest `n' such that at ** least half the slots between 0 and n are in use. ** Hash uses a mix of chained scatter table with Brent's variation. ** A main invariant of these tables is that, if an element is not ** in its main position (i.e. the `original' position that its hash gives ** to it), then the colliding element is in its own main position. ** In other words, there are collisions only when two elements have the ** same main position (i.e. the same hash values for that table size). ** Because of that, the load factor of these tables can be 100% without ** performance penalties. */ #include <string.h> #define ltable_c #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "ltable.h" /* ** max size of array part is 2^MAXBITS */ #if BITS_INT > 26 #define MAXBITS 24 #else #define MAXBITS (BITS_INT-2) #endif /* check whether `x' < 2^MAXBITS */ #define toobig(x) ((((x)-1) >> MAXBITS) != 0) /* function to convert a lua_Number to int (with any rounding method) */ #ifndef lua_number2int #define lua_number2int(i,n) ((i)=(int)(n)) #endif #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) #define hashstr(t,str) hashpow2(t, (str)->tsv.hash) #define hashboolean(t,p) hashpow2(t, p) /* ** for some types, it is better to avoid modulus by power of 2, as ** they tend to have many 2 factors. */ #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) #define hashpointer(t,p) hashmod(t, IntPoint(p)) /* ** number of ints inside a lua_Number */ #define numints cast(int, sizeof(lua_Number)/sizeof(int)) /* ** hash for lua_Numbers */ static Node *hashnum (const Table *t, lua_Number n) { unsigned int a[numints]; int i; n += 1; /* normalize number (avoid -0) */ lua_assert(sizeof(a) <= sizeof(n)); memcpy(a, &n, sizeof(a)); for (i = 1; i < numints; i++) a[0] += a[i]; return hashmod(t, cast(lu_hash, a[0])); } /* ** returns the `main' position of an element in a table (that is, the index ** of its hash value) */ Node *luaH_mainposition (const Table *t, const TObject *key) { switch (ttype(key)) { case LUA_TNUMBER: return hashnum(t, nvalue(key)); case LUA_TSTRING: return hashstr(t, tsvalue(key)); case LUA_TBOOLEAN: return hashboolean(t, bvalue(key)); case LUA_TLIGHTUSERDATA: return hashpointer(t, pvalue(key)); default: return hashpointer(t, gcvalue(key)); } } /* ** returns the index for `key' if `key' is an appropriate key to live in ** the array part of the table, -1 otherwise. */ static int arrayindex (const TObject *key) { if (ttisnumber(key)) { int k; lua_number2int(k, (nvalue(key))); if (cast(lua_Number, k) == nvalue(key) && k >= 1 && !toobig(k)) return k; } return -1; /* `key' did not match some condition */ } /* ** returns the index of a `key' for table traversals. First goes all ** elements in the array part, then elements in the hash part. The ** beginning and end of a traversal are signalled by -1. */ static int luaH_index (lua_State *L, Table *t, StkId key) { int i; if (ttisnil(key)) return -1; /* first iteration */ i = arrayindex(key); if (0 <= i && i <= t->sizearray) { /* is `key' inside array part? */ return i-1; /* yes; that's the index (corrected to C) */ } else { const TObject *v = luaH_get(t, key); if (v == &luaO_nilobject) luaG_runerror(L, "invalid key for `next'"); i = cast(int, (cast(const lu_byte *, v) - cast(const lu_byte *, gval(gnode(t, 0)))) / sizeof(Node)); return i + t->sizearray; /* hash elements are numbered after array ones */ } } int luaH_next (lua_State *L, Table *t, StkId key) { int i = luaH_index(L, t, key); /* find original element */ for (i++; i < t->sizearray; i++) { /* try first array part */ if (!ttisnil(&t->array[i])) { /* a non-nil value? */ setnvalue(key, cast(lua_Number, i+1)); setobj2s(key+1, &t->array[i]); return 1; } } for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ setobj2s(key, gkey(gnode(t, i))); setobj2s(key+1, gval(gnode(t, i))); return 1; } } return 0; /* no more elements */ } /* ** {============================================================= ** Rehash ** ============================================================== */ static void computesizes (int nums[], int ntotal, int *narray, int *nhash) { int i; int a = nums[0]; /* number of elements smaller than 2^i */ int na = a; /* number of elements to go to array part */ int n = (na == 0) ? -1 : 0; /* (log of) optimal size for array part */ for (i = 1; a < *narray && *narray >= twoto(i-1); i++) { if (nums[i] > 0) { a += nums[i]; if (a >= twoto(i-1)) { /* more than half elements in use? */ n = i; na = a; } } } lua_assert(na <= *narray && *narray <= ntotal); *nhash = ntotal - na; *narray = (n == -1) ? 0 : twoto(n); lua_assert(na <= *narray && na >= *narray/2); } static void numuse (const Table *t, int *narray, int *nhash) { int nums[MAXBITS+1]; int i, lg; int totaluse = 0; /* count elements in array part */ for (i=0, lg=0; lg<=MAXBITS; lg++) { /* for each slice [2^(lg-1) to 2^lg) */ int ttlg = twoto(lg); /* 2^lg */ if (ttlg > t->sizearray) { ttlg = t->sizearray; if (i >= ttlg) break; } nums[lg] = 0; for (; i<ttlg; i++) { if (!ttisnil(&t->array[i])) { nums[lg]++; totaluse++; } } } for (; lg<=MAXBITS; lg++) nums[lg] = 0; /* reset other counts */ *narray = totaluse; /* all previous uses were in array part */ /* count elements in hash part */ i = sizenode(t); while (i--) { Node *n = &t->node[i]; if (!ttisnil(gval(n))) { int k = arrayindex(gkey(n)); if (k >= 0) { /* is `key' an appropriate array index? */ nums[luaO_log2(k-1)+1]++; /* count as such */ (*narray)++; } totaluse++; } } computesizes(nums, totaluse, narray, nhash); } static void setarrayvector (lua_State *L, Table *t, int size) { int i; luaM_reallocvector(L, t->array, t->sizearray, size, TObject); for (i=t->sizearray; i<size; i++) setnilvalue(&t->array[i]); t->sizearray = size; } static void setnodevector (lua_State *L, Table *t, int lsize) { int i; int size = twoto(lsize); if (lsize > MAXBITS) luaG_runerror(L, "table overflow"); if (lsize == 0) { /* no elements to hash part? */ t->node = G(L)->dummynode; /* use common `dummynode' */ lua_assert(ttisnil(gkey(t->node))); /* assert invariants: */ lua_assert(ttisnil(gval(t->node))); lua_assert(t->node->next == NULL); /* (`dummynode' must be empty) */ } else { t->node = luaM_newvector(L, size, Node); for (i=0; i<size; i++) { t->node[i].next = NULL; setnilvalue(gkey(gnode(t, i))); setnilvalue(gval(gnode(t, i))); } } t->lsizenode = cast(lu_byte, lsize); t->firstfree = gnode(t, size-1); /* first free position to be used */ } static void resize (lua_State *L, Table *t, int nasize, int nhsize) { int i; int oldasize = t->sizearray; int oldhsize = t->lsizenode; Node *nold; Node temp[1]; if (oldhsize) nold = t->node; /* save old hash ... */ else { /* old hash is `dummynode' */ lua_assert(t->node == G(L)->dummynode); temp[0] = t->node[0]; /* copy it to `temp' */ nold = temp; setnilvalue(gkey(G(L)->dummynode)); /* restate invariant */ setnilvalue(gval(G(L)->dummynode)); lua_assert(G(L)->dummynode->next == NULL); } if (nasize > oldasize) /* array part must grow? */ setarrayvector(L, t, nasize); /* create new hash part with appropriate size */ setnodevector(L, t, nhsize); /* re-insert elements */ if (nasize < oldasize) { /* array part must shrink? */ t->sizearray = nasize; /* re-insert elements from vanishing slice */ for (i=nasize; i<oldasize; i++) { if (!ttisnil(&t->array[i])) setobjt2t(luaH_setnum(L, t, i+1), &t->array[i]); } /* shrink array */ luaM_reallocvector(L, t->array, oldasize, nasize, TObject); } /* re-insert elements in hash part */ for (i = twoto(oldhsize) - 1; i >= 0; i--) { Node *old = nold+i; if (!ttisnil(gval(old))) setobjt2t(luaH_set(L, t, gkey(old)), gval(old)); } if (oldhsize) luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */ } static void rehash (lua_State *L, Table *t) { int nasize, nhsize; numuse(t, &nasize, &nhsize); /* compute new sizes for array and hash parts */ resize(L, t, nasize, luaO_log2(nhsize)+1); } /* ** }============================================================= */ Table *luaH_new (lua_State *L, int narray, int lnhash) { Table *t = luaM_new(L, Table); luaC_link(L, valtogco(t), LUA_TTABLE); t->metatable = hvalue(defaultmeta(L)); t->flags = cast(lu_byte, ~0); /* temporary values (kept only if some malloc fails) */ t->array = NULL; t->sizearray = 0; t->lsizenode = 0; t->node = NULL; setarrayvector(L, t, narray); setnodevector(L, t, lnhash); return t; } void luaH_free (lua_State *L, Table *t) { if (t->lsizenode) luaM_freearray(L, t->node, sizenode(t), Node); luaM_freearray(L, t->array, t->sizearray, TObject); luaM_freelem(L, t); } #if 0 /* ** try to remove an element from a hash table; cannot move any element ** (because gc can call `remove' during a table traversal) */ void luaH_remove (Table *t, Node *e) { Node *mp = luaH_mainposition(t, gkey(e)); if (e != mp) { /* element not in its main position? */ while (mp->next != e) mp = mp->next; /* find previous */ mp->next = e->next; /* remove `e' from its list */ } else { if (e->next != NULL) ?? } lua_assert(ttisnil(gval(node))); setnilvalue(gkey(e)); /* clear node `e' */ e->next = NULL; } #endif /* ** inserts a new key into a hash table; first, check whether key's main ** position is free. If not, check whether colliding node is in its main ** position or not: if it is not, move colliding node to an empty place and ** put new key in its main position; otherwise (colliding node is in its main ** position), new key goes to an empty position. */ static TObject *newkey (lua_State *L, Table *t, const TObject *key) { TObject *val; Node *mp = luaH_mainposition(t, key); if (!ttisnil(gval(mp))) { /* main position is not free? */ Node *othern = luaH_mainposition(t, gkey(mp)); /* `mp' of colliding node */ Node *n = t->firstfree; /* get a free place */ if (othern != mp) { /* is colliding node out of its main position? */ /* yes; move colliding node into free position */ while (othern->next != mp) othern = othern->next; /* find previous */ othern->next = n; /* redo the chain with `n' in place of `mp' */ *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ mp->next = NULL; /* now `mp' is free */ setnilvalue(gval(mp)); } else { /* colliding node is in its own main position */ /* new node will go into free position */ n->next = mp->next; /* chain new position */ mp->next = n; mp = n; } } setobj2t(gkey(mp), key); /* write barrier */ lua_assert(ttisnil(gval(mp))); for (;;) { /* correct `firstfree' */ if (ttisnil(gkey(t->firstfree))) return gval(mp); /* OK; table still has a free place */ else if (t->firstfree == t->node) break; /* cannot decrement from here */ else (t->firstfree)--; } /* no more free places; must create one */ setbvalue(gval(mp), 0); /* avoid new key being removed */ rehash(L, t); /* grow table */ val = cast(TObject *, luaH_get(t, key)); /* get new position */ lua_assert(ttisboolean(val)); setnilvalue(val); return val; } /* ** generic search function */ static const TObject *luaH_getany (Table *t, const TObject *key) { if (ttisnil(key)) return &luaO_nilobject; else { Node *n = luaH_mainposition(t, key); do { /* check whether `key' is somewhere in the chain */ if (luaO_rawequalObj(gkey(n), key)) return gval(n); /* that's it */ else n = n->next; } while (n); return &luaO_nilobject; } } /* ** search function for integers */ const TObject *luaH_getnum (Table *t, int key) { if (1 <= key && key <= t->sizearray) return &t->array[key-1]; else { lua_Number nk = cast(lua_Number, key); Node *n = hashnum(t, nk); do { /* check whether `key' is somewhere in the chain */ if (ttisnumber(gkey(n)) && nvalue(gkey(n)) == nk) return gval(n); /* that's it */ else n = n->next; } while (n); return &luaO_nilobject; } } /* ** search function for strings */ const TObject *luaH_getstr (Table *t, TString *key) { Node *n = hashstr(t, key); do { /* check whether `key' is somewhere in the chain */ if (ttisstring(gkey(n)) && tsvalue(gkey(n)) == key) return gval(n); /* that's it */ else n = n->next; } while (n); return &luaO_nilobject; } /* ** main search function */ const TObject *luaH_get (Table *t, const TObject *key) { switch (ttype(key)) { case LUA_TSTRING: return luaH_getstr(t, tsvalue(key)); case LUA_TNUMBER: { int k; lua_number2int(k, (nvalue(key))); if (cast(lua_Number, k) == nvalue(key)) /* is an integer index? */ return luaH_getnum(t, k); /* use specialized version */ /* else go through */ } default: return luaH_getany(t, key); } } TObject *luaH_set (lua_State *L, Table *t, const TObject *key) { const TObject *p = luaH_get(t, key); t->flags = 0; if (p != &luaO_nilobject) return cast(TObject *, p); else { if (ttisnil(key)) luaG_runerror(L, "table index is nil"); else if (ttisnumber(key) && nvalue(key) != nvalue(key)) luaG_runerror(L, "table index is NaN"); return newkey(L, t, key); } } TObject *luaH_setnum (lua_State *L, Table *t, int key) { const TObject *p = luaH_getnum(t, key); if (p != &luaO_nilobject) return cast(TObject *, p); else { TObject k; setnvalue(&k, cast(lua_Number, key)); return newkey(L, t, &k); } } --- NEW FILE: ldebug.c --- /* ** $Id: ldebug.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Debug Interface ** See Copyright Notice in lua.h */ #include <stdlib.h> #include <string.h> #define ldebug_c #include "lua.h" #include "lapi.h" #include "lcode.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lobject.h" #include "lopcodes.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lvm.h" static const char *getfuncname (CallInfo *ci, const char **name); #define isLua(ci) (!((ci)->state & CI_C)) static int currentpc (CallInfo *ci) { if (!isLua(ci)) return -1; /* function is not a Lua function? */ if (ci->state & CI_HASFRAME) /* function has a frame? */ ci->u.l.savedpc = *ci->u.l.pc; /* use `pc' from there */ /* function's pc is saved */ return pcRel(ci->u.l.savedpc, ci_func(ci)->l.p); } static int currentline (CallInfo *ci) { int pc = currentpc(ci); if (pc < 0) return -1; /* only active lua functions have current-line information */ else return getline(ci_func(ci)->l.p, pc); } void luaG_inithooks (lua_State *L) { CallInfo *ci; for (ci = L->ci; ci != L->base_ci; ci--) /* update all `savedpc's */ currentpc(ci); L->hookinit = 1; } /* ** this function can be called asynchronous (e.g. during a signal) */ LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { if (func == NULL || mask == 0) { /* turn off hooks? */ mask = 0; func = NULL; } L->hook = func; L->basehookcount = count; resethookcount(L); L->hookmask = cast(lu_byte, mask); L->hookinit = 0; return 1; } LUA_API lua_Hook lua_gethook (lua_State *L) { return L->hook; } LUA_API int lua_gethookmask (lua_State *L) { return L->hookmask; } LUA_API int lua_gethookcount (lua_State *L) { return L->basehookcount; } LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { int status; CallInfo *ci; lua_lock(L); for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) { level--; if (!(ci->state & CI_C)) /* Lua function? */ level -= ci->u.l.tailcalls; /* skip lost tail calls */ } if (level > 0 || ci == L->base_ci) status = 0; /* there is no such level */ else if (level < 0) { /* level is of a lost tail call */ status = 1; ar->i_ci = 0; } else { status = 1; ar->i_ci = ci - L->base_ci; } lua_unlock(L); return status; } static Proto *getluaproto (CallInfo *ci) { return (isLua(ci) ? ci_func(ci)->l.p : NULL); } LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { const char *name; CallInfo *ci; Proto *fp; lua_lock(L); name = NULL; ci = L->base_ci + ar->i_ci; fp = getluaproto(ci); if (fp) { /* is a Lua function? */ name = luaF_getlocalname(fp, n, currentpc(ci)); if (name) luaA_pushobject(L, ci->base+(n-1)); /* push value */ } lua_unlock(L); return name; } LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { const char *name; CallInfo *ci; Proto *fp; lua_lock(L); name = NULL; ci = L->base_ci + ar->i_ci; fp = getluaproto(ci); L->top--; /* pop new value */ if (fp) { /* is a Lua function? */ name = luaF_getlocalname(fp, n, currentpc(ci)); if (!name || name[0] == '(') /* `(' starts private locals */ name = NULL; else setobjs2s(ci->base+(n-1), L->top); } lua_unlock(L); return name; } static void funcinfo (lua_Debug *ar, StkId func) { Closure *cl = clvalue(func); if (cl->c.isC) { ar->source = "=[C]"; ar->linedefined = -1; ar->what = "C"; } else { ar->source = getstr(cl->l.p->source); ar->linedefined = cl->l.p->lineDefined; ar->what = (ar->linedefined == 0) ? "main" : "Lua"; } luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); } static const char *travglobals (lua_State *L, const TObject *o) { Table *g = hvalue(gt(L)); int i = sizenode(g); while (i--) { Node *n = gnode(g, i); if (luaO_rawequalObj(o, gval(n)) && ttisstring(gkey(n))) return getstr(tsvalue(gkey(n))); } return NULL; } static void info_tailcall (lua_State *L, lua_Debug *ar) { ar->name = ar->namewhat = ""; ar->what = "tail"; ar->linedefined = ar->currentline = -1; ar->source = "=(tail call)"; luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); ar->nups = 0; setnilvalue(L->top); } static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, StkId f, CallInfo *ci) { int status = 1; for (; *what; what++) { switch (*what) { case 'S': { funcinfo(ar, f); break; } case 'l': { ar->currentline = (ci) ? currentline(ci) : -1; break; } case 'u': { ar->nups = clvalue(f)->c.nupvalues; break; } case 'n': { ar->namewhat = (ci) ? getfuncname(ci, &ar->name) : NULL; if (ar->namewhat == NULL) { /* try to find a global name */ if ((ar->name = travglobals(L, f)) != NULL) ar->namewhat = "global"; else ar->namewhat = ""; /* not found */ } break; } case 'f': { setobj2s(L->top, f); break; } default: status = 0; /* invalid option */ } } return status; } LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { int status = 1; lua_lock(L); if (*what == '>') { StkId f = L->top - 1; if (!ttisfunction(f)) luaG_runerror(L, "value for `lua_getinfo' is not a function"); status = auxgetinfo(L, what + 1, ar, f, NULL); L->top--; /* pop function */ } else if (ar->i_ci != 0) { /* no tail call? */ CallInfo *ci = L->base_ci + ar->i_ci; lua_assert(ttisfunction(ci->base - 1)); status = auxgetinfo(L, what, ar, ci->base - 1, ci); } else info_tailcall(L, ar); if (strchr(what, 'f')) incr_top(L); lua_unlock(L); return status; } /* ** {====================================================== ** Symbolic Execution and code checker ** ======================================================= */ #define check(x) if (!(x)) return 0; #define checkjump(pt,pc) check(0 <= pc && pc < pt->sizecode) #define checkreg(pt,reg) check((reg) < (pt)->maxstacksize) static int precheck (const Proto *pt) { check(pt->maxstacksize <= MAXSTACK); check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0); lua_assert(pt->numparams+pt->is_vararg <= pt->maxstacksize); check(GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN); return 1; } static int checkopenop (const Proto *pt, int pc) { Instruction i = pt->code[pc+1]; switch (GET_OPCODE(i)) { case OP_CALL: case OP_TAILCALL: case OP_RETURN: { check(GETARG_B(i) == 0); return 1; } case OP_SETLISTO: return 1; default: return 0; /* invalid instruction after an open call */ } } static int checkRK (const Proto *pt, int r) { return (r < pt->maxstacksize || (r >= MAXSTACK && r-MAXSTACK < pt->sizek)); } static Instruction luaG_symbexec (const Proto *pt, int lastpc, int reg) { int pc; int last; /* stores position of last instruction that changed `reg' */ last = pt->sizecode-1; /* points to final return (a `neutral' instruction) */ check(precheck(pt)); for (pc = 0; pc < lastpc; pc++) { const Instruction i = pt->code[pc]; OpCode op = GET_OPCODE(i); int a = GETARG_A(i); int b = 0; int c = 0; checkreg(pt, a); switch (getOpMode(op)) { case iABC: { b = GETARG_B(i); c = GETARG_C(i); if (testOpMode(op, OpModeBreg)) { checkreg(pt, b); } else if (testOpMode(op, OpModeBrk)) check(checkRK(pt, b)); if (testOpMode(op, OpModeCrk)) check(checkRK(pt, c)); break; } case iABx: { b = GETARG_Bx(i); if (testOpMode(op, OpModeK)) check(b < pt->sizek); break; } case iAsBx: { b = GETARG_sBx(i); break; } } if (testOpMode(op, OpModesetA)) { if (a == reg) last = pc; /* change register `a' */ } if (testOpMode(op, OpModeT)) { check(pc+2 < pt->sizecode); /* check skip */ check(GET_OPCODE(pt->code[pc+1]) == OP_JMP); } switch (op) { case OP_LOADBOOL: { check(c == 0 || pc+2 < pt->sizecode); /* check its jump */ break; } case OP_LOADNIL: { if (a <= reg && reg <= b) last = pc; /* set registers from `a' to `b' */ break; } case OP_GETUPVAL: case OP_SETUPVAL: { check(b < pt->nups); break; } case OP_GETGLOBAL: case OP_SETGLOBAL: { check(ttisstring(&pt->k[b])); break; } case OP_SELF: { checkreg(pt, a+1); if (reg == a+1) last = pc; break; } case OP_CONCAT: { /* `c' is a register, and at least two operands */ check(c < MAXSTACK && b < c); break; } case OP_TFORLOOP: checkreg(pt, a+c+5); if (reg >= a) last = pc; /* affect all registers above base */ /* go through */ case OP_FORLOOP: checkreg(pt, a+2); /* go through */ case OP_JMP: { int dest = pc+1+b; check(0 <= dest && dest < pt->sizecode); /* not full check and jump is forward and do not skip `lastpc'? */ if (reg != NO_REG && pc < dest && dest <= lastpc) pc += b; /* do the jump */ break; } case OP_CALL: case OP_TAILCALL: { if (b != 0) { checkreg(pt, a+b-1); } c--; /* c = num. returns */ if (c == LUA_MULTRET) { check(checkopenop(pt, pc)); } else if (c != 0) checkreg(pt, a+c-1); if (reg >= a) last = pc; /* affect all registers above base */ break; } case OP_RETURN: { b--; /* b = num. returns */ if (b > 0) checkreg(pt, a+b-1); break; } case OP_SETLIST: { checkreg(pt, a + (b&(LFIELDS_PER_FLUSH-1)) + 1); break; } case OP_CLOSURE: { int nup; check(b < pt->sizep); nup = pt->p[b]->nups; check(pc + nup < pt->sizecode); for (; nup>0; nup--) { OpCode op1 = GET_OPCODE(pt->code[pc+nup]); check(op1 == OP_GETUPVAL || op1 == OP_MOVE); } break; } default: break; } } return pt->code[last]; } #undef check #undef checkjump #undef checkreg /* }====================================================== */ int luaG_checkcode (const Proto *pt) { return luaG_symbexec(pt, pt->sizecode, NO_REG); } static const char *kname (Proto *p, int c) { c = c - MAXSTACK; if (c >= 0 && ttisstring(&p->k[c])) return svalue(&p->k[c]); else return "?"; } static const char *getobjname (CallInfo *ci, int stackpos, const char **name) { if (isLua(ci)) { /* a Lua function? */ Proto *p = ci_func(ci)->l.p; int pc = currentpc(ci); Instruction i; *name = luaF_getlocalname(p, stackpos+1, pc); if (*name) /* is a local? */ return "local"; i = luaG_symbexec(p, pc, stackpos); /* try symbolic execution */ lua_assert(pc != -1); switch (GET_OPCODE(i)) { case OP_GETGLOBAL: { int g = GETARG_Bx(i); /* global index */ lua_assert(ttisstring(&p->k[g])); *name = svalue(&p->k[g]); return "global"; } case OP_MOVE: { int a = GETARG_A(i); int b = GETARG_B(i); /* move from `b' to `a' */ if (b < a) return getobjname(ci, b, name); /* get name for `b' */ break; } case OP_GETTABLE: { int k = GETARG_C(i); /* key index */ *name = kname(p, k); return "field"; } case OP_SELF: { int k = GETARG_C(i); /* key index */ *name = kname(p, k); return "method"; } default: break; } } return NULL; /* no useful name found */ } static const char *getfuncname (CallInfo *ci, const char **name) { Instruction i; if ((isLua(ci) && ci->u.l.tailcalls > 0) || !isLua(ci - 1)) return NULL; /* calling function is not Lua (or is unknown) */ ci--; /* calling function */ i = ci_func(ci)->l.p->code[currentpc(ci)]; if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL) return getobjname(ci, GETARG_A(i), name); else return NULL; /* no useful name can be found */ } /* only ANSI way to check whether a pointer points to an array */ static int isinstack (CallInfo *ci, const TObject *o) { StkId p; for (p = ci->base; p < ci->top; p++) if (o == p) return 1; return 0; } void luaG_typeerror (lua_State *L, const TObject *o, const char *op) { const char *name = NULL; const char *t = luaT_typenames[ttype(o)]; const char *kind = (isinstack(L->ci, o)) ? getobjname(L->ci, o - L->base, &name) : NULL; if (kind) luaG_runerror(L, "attempt to %s %s `%s' (a %s value)", op, kind, name, t); else luaG_runerror(L, "attempt to %s a %s value", op, t); } void luaG_concaterror (lua_State *L, StkId p1, StkId p2) { if (ttisstring(p1)) p1 = p2; lua_assert(!ttisstring(p1)); luaG_typeerror(L, p1, "concatenate"); } void luaG_aritherror (lua_State *L, const TObject *p1, const TObject *p2) { TObject temp; if (luaV_tonumber(p1, &temp) == NULL) p2 = p1; /* first operand is wrong */ luaG_typeerror(L, p2, "perform arithmetic on"); } int luaG_ordererror (lua_State *L, const TObject *p1, const TObject *p2) { const char *t1 = luaT_typenames[ttype(p1)]; const char *t2 = luaT_typenames[ttype(p2)]; if (t1[2] == t2[2]) luaG_runerror(L, "attempt to compare two %s values", t1); else luaG_runerror(L, "attempt to compare %s with %s", t1, t2); return 0; } static void addinfo (lua_State *L, const char *msg) { CallInfo *ci = L->ci; if (isLua(ci)) { /* is Lua code? */ char buff[LUA_IDSIZE]; /* add file:line information */ int line = currentline(ci); luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE); luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); } } void luaG_errormsg (lua_State *L) { if (L->errfunc != 0) { /* is there an error handling function? */ StkId errfunc = restorestack(L, L->errfunc); if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); setobjs2s(L->top, L->top - 1); /* move argument */ setobjs2s(L->top - 1, errfunc); /* push function */ incr_top(L); luaD_call(L, L->top - 2, 1); /* call it */ } luaD_throw(L, LUA_ERRRUN); } void luaG_runerror (lua_State *L, const char *fmt, ...) { va_list argp; va_start(argp, fmt); addinfo(L, luaO_pushvfstring(L, fmt, argp)); va_end(argp); luaG_errormsg(L); } --- NEW FILE: lobject.h --- /* ** $Id: lobject.h,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Type definitions for Lua objects ** See Copyright Notice in lua.h */ #ifndef lobject_h #define lobject_h #include "llimits.h" #include "lua.h" /* tags for values visible from Lua */ #define NUM_TAGS LUA_TTHREAD /* ** Extra tags for non-values */ #define LUA_TPROTO (NUM_TAGS+1) #define LUA_TUPVAL (NUM_TAGS+2) /* ** Union of all collectable objects */ typedef union GCObject GCObject; /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked /* ** Common header in struct form */ typedef struct GCheader { CommonHeader; } GCheader; /* ** Union of all Lua values */ typedef union { GCObject *gc; void *p; lua_Number n; int b; } Value; /* ** Lua values (or `tagged objects') */ typedef struct lua_TObject { int tt; Value value; } TObject; /* Macros to test type */ #define ttisnil(o) (ttype(o) == LUA_TNIL) #define ttisnumber(o) (ttype(o) == LUA_TNUMBER) #define ttisstring(o) (ttype(o) == LUA_TSTRING) #define ttistable(o) (ttype(o) == LUA_TTABLE) #define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) #define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) #define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) #define ttisthread(o) (ttype(o) == LUA_TTHREAD) #define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) /* Macros to access values */ #define ttype(o) ((o)->tt) #define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) #define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) #define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) #define tsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) #define uvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) #define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) #define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) #define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) #define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) /* Macros to set values */ #define setnvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TNUMBER; i_o->value.n=(x); } #define chgnvalue(obj,x) \ check_exp(ttype(obj)==LUA_TNUMBER, (obj)->value.n=(x)) #define setpvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TLIGHTUSERDATA; i_o->value.p=(x); } #define setbvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TBOOLEAN; i_o->value.b=(x); } #define setsvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TSTRING; \ i_o->value.gc=cast(GCObject *, (x)); \ lua_assert(i_o->value.gc->gch.tt == LUA_TSTRING); } #define setuvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TUSERDATA; \ i_o->value.gc=cast(GCObject *, (x)); \ lua_assert(i_o->value.gc->gch.tt == LUA_TUSERDATA); } #define setthvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TTHREAD; \ i_o->value.gc=cast(GCObject *, (x)); \ lua_assert(i_o->value.gc->gch.tt == LUA_TTHREAD); } #define setclvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TFUNCTION; \ i_o->value.gc=cast(GCObject *, (x)); \ lua_assert(i_o->value.gc->gch.tt == LUA_TFUNCTION); } #define sethvalue(obj,x) \ { TObject *i_o=(obj); i_o->tt=LUA_TTABLE; \ i_o->value.gc=cast(GCObject *, (x)); \ lua_assert(i_o->value.gc->gch.tt == LUA_TTABLE); } #define setnilvalue(obj) ((obj)->tt=LUA_TNIL) /* ** for internal debug only */ #define checkconsistency(obj) \ lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt)) #define setobj(obj1,obj2) \ { const TObject *o2=(obj2); TObject *o1=(obj1); \ checkconsistency(o2); \ o1->tt=o2->tt; o1->value = o2->value; } /* ** different types of sets, according to destination */ /* from stack to (same) stack */ #define setobjs2s setobj /* to stack (not from same stack) */ #define setobj2s setobj #define setsvalue2s setsvalue /* from table to same table */ #define setobjt2t setobj /* to table */ #define setobj2t setobj /* to new object */ #define setobj2n setobj #define setsvalue2n setsvalue #define setttype(obj, tt) (ttype(obj) = (tt)) #define iscollectable(o) (ttype(o) >= LUA_TSTRING) typedef TObject *StkId; /* index to stack elements */ /* ** String headers for string table */ typedef union TString { L_Umaxalign dummy; /* ensures maximum alignment for strings */ struct { CommonHeader; lu_byte reserved; lu_hash hash; size_t len; } tsv; } TString; #define getstr(ts) cast(const char *, (ts) + 1) #define svalue(o) getstr(tsvalue(o)) typedef union Udata { L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ struct { CommonHeader; struct Table *metatable; size_t len; } uv; } Udata; /* ** Function Prototypes */ typedef struct Proto { CommonHeader; TObject *k; /* constants used by the function */ Instruction *code; struct Proto **p; /* functions defined inside the function */ int *lineinfo; /* map from opcodes to source lines */ struct LocVar *locvars; /* information about local variables */ TString **upvalues; /* upvalue names */ TString *source; int sizeupvalues; int sizek; /* size of `k' */ int sizecode; int sizelineinfo; int sizep; /* size of `p' */ int sizelocvars; int lineDefined; GCObject *gclist; lu_byte nups; /* number of upvalues */ lu_byte numparams; lu_byte is_vararg; lu_byte maxstacksize; } Proto; typedef struct LocVar { TString *varname; int startpc; /* first point where variable is active */ int endpc; /* first point where variable is dead */ } LocVar; /* ** Upvalues */ typedef struct UpVal { CommonHeader; TObject *v; /* points to stack or to its own value */ TObject value; /* the value (when closed) */ } UpVal; /* ** Closures */ #define ClosureHeader \ CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist typedef struct CClosure { ClosureHeader; lua_CFunction f; TObject upvalue[1]; } CClosure; typedef struct LClosure { ClosureHeader; struct Proto *p; TObject g; /* global table for this closure */ UpVal *upvals[1]; } LClosure; typedef union Closure { CClosure c; LClosure l; } Closure; #define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC) #define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC) /* ** Tables */ typedef struct Node { TObject i_key; TObject i_val; struct Node *next; /* for chaining */ } Node; typedef struct Table { CommonHeader; lu_byte flags; /* 1<<p means tagmethod(p) is not present */ lu_byte lsizenode; /* log2 of size of `node' array */ struct Table *metatable; TObject *array; /* array part */ Node *node; Node *firstfree; /* this position is free; all positions after it are full */ GCObject *gclist; int sizearray; /* size of `array' array */ } Table; /* ** `module' operation for hashing (size is always a power of 2) */ #define lmod(s,size) \ check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))) #define twoto(x) (1<<(x)) #define sizenode(t) (twoto((t)->lsizenode)) extern const TObject luaO_nilobject; int luaO_log2 (unsigned int x); int luaO_int2fb (unsigned int x); #define fb2int(x) (((x) & 7) << ((x) >> 3)) int luaO_rawequalObj (const TObject *t1, const TObject *t2); int luaO_str2d (const char *s, lua_Number *result); const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp); const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); void luaO_chunkid (char *out, const char *source, int len); #endif --- NEW FILE: lundump.c --- /* ** $Id: lundump.c,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** load pre-compiled Lua chunks ** See Copyright Notice in lua.h */ #define lundump_c #include "lua.h" #include "ldebug.h" #include "lfunc.h" #include "lmem.h" #include "lopcodes.h" #include "lstring.h" #include "lundump.h" #include "lzio.h" #define LoadByte (lu_byte) ezgetc typedef struct { lua_State* L; ZIO* Z; Mbuffer* b; int swap; const char* name; } LoadState; static void unexpectedEOZ (LoadState* S) { luaG_runerror(S->L,"unexpected end of file in %s",S->name); } static int ezgetc (LoadState* S) { int c=zgetc(S->Z); if (c==EOZ) unexpectedEOZ(S); return c; } static void ezread (LoadState* S, void* b, int n) { int r=luaZ_read(S->Z,b,n); if (r!=0) unexpectedEOZ(S); } static void LoadBlock (LoadState* S, void* b, size_t size) { if (S->swap) { char* p=(char*) b+size-1; int n=size; while (n--) *p--=(char)ezgetc(S); } else ezread(S,b,size); } static void LoadVector (LoadState* S, void* b, int m, size_t size) { if (S->swap) { char* q=(char*) b; while (m--) { char* p=q+size-1; int n=size; while (n--) *p--=(char)ezgetc(S); q+=size; } } else ezread(S,b,m*size); } static int LoadInt (LoadState* S) { int x; LoadBlock(S,&x,sizeof(x)); if (x<0) luaG_runerror(S->L,"bad integer in %s",S->name); return x; } static size_t LoadSize (LoadState* S) { size_t x; LoadBlock(S,&x,sizeof(x)); return x; } static lua_Number LoadNumber (LoadState* S) { lua_Number x; LoadBlock(S,&x,sizeof(x)); return x; } static TString* LoadString (LoadState* S) { size_t size=LoadSize(S); if (size==0) return NULL; else { char* s=luaZ_openspace(S->L,S->b,size); ezread(S,s,size); return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */ } } static void LoadCode (LoadState* S, Proto* f) { int size=LoadInt(S); f->code=luaM_newvector(S->L,size,Instruction); f->sizecode=size; LoadVector(S,f->code,size,sizeof(*f->code)); } static void LoadLocals (LoadState* S, Proto* f) { int i,n; n=LoadInt(S); f->locvars=luaM_newvector(S->L,n,LocVar); f->sizelocvars=n; for (i=0; i<n; i++) { f->locvars[i].varname=LoadString(S); f->locvars[i].startpc=LoadInt(S); f->locvars[i].endpc=LoadInt(S); } } static void LoadLines (LoadState* S, Proto* f) { int size=LoadInt(S); f->lineinfo=luaM_newvector(S->L,size,int); f->sizelineinfo=size; LoadVector(S,f->lineinfo,size,sizeof(*f->lineinfo)); } static void LoadUpvalues (LoadState* S, Proto* f) { int i,n; n=LoadInt(S); if (n!=0 && n!=f->nups) luaG_runerror(S->L,"bad nupvalues in %s: read %d; expected %d", S->name,n,f->nups); f->upvalues=luaM_newvector(S->L,n,TString*); f->sizeupvalues=n; for (i=0; i<n; i++) f->upvalues[i]=LoadString(S); } static Proto* LoadFunction (LoadState* S, TString* p); static void LoadConstants (LoadState* S, Proto* f) { int i,n; n=LoadInt(S); f->k=luaM_newvector(S->L,n,TObject); f->sizek=n; for (i=0; i<n; i++) { TObject* o=&f->k[i]; int t=LoadByte(S); switch (t) { case LUA_TNUMBER: setnvalue(o,LoadNumber(S)); break; case LUA_TSTRING: setsvalue2n(o,LoadString(S)); break; case LUA_TNIL: setnilvalue(o); break; default: luaG_runerror(S->L,"bad constant type (%d) in %s",t,S->name); break; } } n=LoadInt(S); f->p=luaM_newvector(S->L,n,Proto*); f->sizep=n; for (i=0; i<n; i++) f->p[i]=LoadFunction(S,f->source); } static Proto* LoadFunction (LoadState* S, TString* p) { Proto* f=luaF_newproto(S->L); f->source=LoadString(S); if (f->source==NULL) f->source=p; f->lineDefined=LoadInt(S); f->nups=LoadByte(S); f->numparams=LoadByte(S); f->is_vararg=LoadByte(S); f->maxstacksize=LoadByte(S); LoadLines(S,f); LoadLocals(S,f); LoadUpvalues(S,f); LoadConstants(S,f); LoadCode(S,f); #ifndef TRUST_BINARIES if (!luaG_checkcode(f)) luaG_runerror(S->L,"bad code in %s",S->name); #endif return f; } static void LoadSignature (LoadState* S) { const char* s=LUA_SIGNATURE; while (*s!=0 && ezgetc(S)==*s) ++s; if (*s!=0) luaG_runerror(S->L,"bad signature in %s",S->name); } static void TestSize (LoadState* S, int s, const char* what) { int r=LoadByte(S); if (r!=s) luaG_runerror(S->L,"virtual machine mismatch in %s: " "size of %s is %d but read %d",S->name,what,s,r); } #define TESTSIZE(s,w) TestSize(S,s,w) #define V(v) v/16,v%16 static void LoadHeader (LoadState* S) { int version; lua_Number x,tx=TEST_NUMBER; LoadSignature(S); version=LoadByte(S); if (version>VERSION) luaG_runerror(S->L,"%s too new: " "read version %d.%d; expected at most %d.%d", S->name,V(version),V(VERSION)); if (version<VERSION0) /* check last major change */ luaG_runerror(S->L,"%s too old: " "read version %d.%d; expected at least %d.%d", S->name,V(version),V(VERSION0)); S->swap=(luaU_endianness()!=LoadByte(S)); /* need to swap bytes? */ TESTSIZE(sizeof(int),"int"); TESTSIZE(sizeof(size_t), "size_t"); TESTSIZE(sizeof(Instruction), "Instruction"); TESTSIZE(SIZE_OP, "OP"); TESTSIZE(SIZE_A, "A"); TESTSIZE(SIZE_B, "B"); TESTSIZE(SIZE_C, "C"); TESTSIZE(sizeof(lua_Number), "number"); x=LoadNumber(S); if ((long)x!=(long)tx) /* disregard errors in last bits of fraction */ luaG_runerror(S->L,"unknown number format in %s",S->name); } static Proto* LoadChunk (LoadState* S) { LoadHeader(S); return LoadFunction(S,NULL); } /* ** load precompiled chunk */ Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff) { LoadState S; const char* s=zname(Z); if (*s=='@' || *s=='=') S.name=s+1; else if (*s==LUA_SIGNATURE[0]) S.name="binary string"; else S.name=s; S.L=L; S.Z=Z; S.b=buff; return LoadChunk(&S); } /* ** find byte order */ int luaU_endianness (void) { int x=1; return *(char*)&x; } --- NEW FILE: lundump.h --- /* ** $Id: lundump.h,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** load pre-compiled Lua chunks ** See Copyright Notice in lua.h */ #ifndef lundump_h #define lundump_h #include "lobject.h" #include "lzio.h" /* load one chunk; from lundump.c */ Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff); /* find byte order; from lundump.c */ int luaU_endianness (void); /* dump one chunk; from ldump.c */ void luaU_dump (lua_State* L, const Proto* Main, lua_Chunkwriter w, void* data); /* print one chunk; from print.c */ void luaU_print (const Proto* Main); /* definitions for headers of binary files */ #define LUA_SIGNATURE "\033Lua" /* binary files start with "<esc>Lua" */ #define VERSION 0x50 /* last format change was in 5.0 */ #define VERSION0 0x50 /* last major change was in 5.0 */ /* a multiple of PI for testing native format */ /* multiplying by 1E7 gives non-trivial integer values */ #define TEST_NUMBER ((lua_Number)3.14159265358979323846E7) #endif --- NEW FILE: lopcodes.h --- /* ** $Id: lopcodes.h,v 1.1 2005/06/06 23:06:16 jrl1 Exp $ ** Opcodes for Lua virtual machine ** See Copyright Notice in lua.h */ #ifndef lopcodes_h #define lopcodes_h #include "llimits.h" /*=========================================================================== We assume that instructions are unsigned numbers. All instructions have an opcode in the first 6 bits. Instructions can have the following fields: `A' : 8 bits `B' : 9 bits `C' : 9 bits `Bx' : 18 bits (`B' and `C' together) `sBx' : signed Bx A signed argument is represented in excess K; that is, the number value is the unsigned value minus K. K is exactly the maximum value for that argument (so that -max is represented by 0, and +max is represented by 2*max), which is half the maximum for the corresponding unsigned argument. ===========================================================================*/ enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */ /* ** size and position of opcode arguments. */ #define SIZE_C 9 #define SIZE_B 9 #define SIZE_Bx (SIZE_C + SIZE_B) #define SIZE_A 8 #define SIZE_OP 6 #define POS_C SIZE_OP #define POS_B (POS_C + SIZE_C) #define POS_Bx POS_C #define POS_A (POS_B + SIZE_B) /* ** limits for opcode arguments. ** we use (signed) int to manipulate most arguments, ** so they must fit in BITS_INT-1 bits (-1 for sign) */ #if SIZE_Bx < BITS_INT-1 #define MAXARG_Bx ((1<<SIZE_Bx)-1) #define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */ #else #define MAXARG_Bx MAX_INT #define MAXARG_sBx MAX_INT #endif #define MAXARG_A ((1<<SIZE_A)-1) #define MAXARG_B ((1<<SIZE_B)-1) #define MAXARG_C ((1<<SIZE_C)-1) /* creates a mask with `n' 1 bits at position `p' */ #define MASK1(n,p) ((~((~(Instruction)0)<<n))<<p) /* creates a mask with `n' 0 bits at position `p' */ #define MASK0(n,p) (~MASK1(n,p)) /* ** the following macros help to manipulate instructions */ #define GET_OPCODE(i) (cast(OpCode, (i)&MASK1(SIZE_OP,0))) #define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,0)) | cast(Instruction, o))) #define GETARG_A(i) (cast(int, (i)>>POS_A)) #define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \ ((cast(Instruction, u)<<POS_A)&MASK1(SIZE_A,POS_A)))) #define GETARG_B(i) (cast(int, ((i)>>POS_B) & MASK1(SIZE_B,0))) #define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \ ((cast(Instruction, b)<<POS_B)&MASK1(SIZE_B,POS_B)))) #define GETARG_C(i) (cast(int, ((i)>>POS_C) & MASK1(SIZE_C,0))) #define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \ ((cast(Instruction, b)<<POS_C)&MASK1(SIZE_C,POS_C)))) #define GETARG_Bx(i) (cast(int, ((i)>>POS_Bx) & MASK1(SIZE_Bx,0))) #define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \ ((cast(Instruction, b)<<POS_Bx)&MASK1(SIZE_Bx,POS_Bx)))) #define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx) #define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx)) #define CREATE_ABC(o,a,b,c) (cast(Instruction, o) \ | (cast(Instruction, a)<<POS_A) \ | (cast(Instruction, b)<<POS_B) \ | (cast(Instruction, c)<<POS_C)) #define CREATE_ABx(o,a,bc) (cast(Instruction, o) \ | (cast(Instruction, a)<<POS_A) \ | (cast(Instruction, bc)<<POS_Bx)) /* ** invalid register that fits in 8 bits */ #define NO_REG MAXARG_A /* ** R(x) - register ** Kst(x) - constant (in constant table) ** RK(x) == if x < MAXSTACK then R(x) else Kst(x-MAXSTACK) */ /* ** grep "ORDER OP" if you change these enums */ typedef enum { /*---------------------------------------------------------------------- name args description ------------------------------------------------------------------------*/ OP_MOVE,/* A B R(A) := R(B) */ OP_LOADK,/* A Bx R(A) := Kst(Bx) */ OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) PC++ */ OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */ OP_GETUPVAL,/* A B R(A) := UpValue[B] */ OP_GETGLOBAL,/* A Bx R(A) := Gbl[Kst(Bx)] */ OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */ OP_SETGLOBAL,/* A Bx Gbl[Kst(Bx)] := R(A) */ OP_SETUPVAL,/* A B UpValue[B] := R(A) */ OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */ OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */ OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */ OP_ADD,/* A B C R(A) := RK(B) + RK(C) */ OP_SUB,/* A B C R(A) := RK(B) - RK(C) */ OP_MUL,/* A B C R(A) := RK(B) * RK(C) */ OP_DIV,/* A B C R(A) := RK(B) / RK(C) */ OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */ OP_UNM,/* A B R(A) := -R(B) */ OP_NOT,/* A B R(A) := not R(B) */ OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */ OP_JMP,/* sBx PC += sBx */ OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ OP_TEST,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-... [truncated message content] |
From: John L. <jr...@us...> - 2005-06-06 23:06:27
|
Update of /cvsroot/wxlua/wxLua/modules/lua/src/luac In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/src/luac Added Files: Makefile README luac.c luac.dsp print.c Log Message: moved files to the modules directory structure --- NEW FILE: README --- This is luac, the Lua compiler. There are man pages for it in both nroff and html in ../../doc. luac translates Lua programs into binary files that can be loaded latter. The main advantages of pre-compiling chunks are: faster loading, protecting source code from user changes, and off-line syntax error detection. luac can also be used to learn about the Lua virtual machine. Usage: /l/luac/luac [options] [filenames]. Available options are: - process stdin -l list -o name output to file `name' (default is "luac.out") -p parse only -s strip debug information -v show version information -- stop handling options luac is also an example of how to use the internals of Lua (politely). --- NEW FILE: luac.dsp --- # Microsoft Developer Studio Project File - Name="luac" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=luac - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "Luac.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "Luac.mak" CFG="luac - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luac - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "luac - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "luac - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "..\..\..\Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /FdRelease\luac.pdb /c # ADD CPP /nologo /MD /W4 /GX /O2 /I "..\..\include" /I ".." /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "LUA_OPNAMES" /D LUACALL=__stdcall /YX /FD /c # ADD BASE RSC /l 0x809 /d "NDEBUG" # ADD RSC /l 0x809 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 /nologo /subsystem:console /machine:I386 # ADD LINK32 /nologo /subsystem:console /machine:I386 !ELSEIF "$(CFG)" == "luac - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "..\..\..\Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /FdDebug\luac.pdb /c # ADD CPP /nologo /MDd /W4 /Gm /GR /GX /ZI /Od /I "..\..\include" /I ".." /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "LUA_OPNAMES" /D LUACALL=__stdcall /YX /FD /GZ /c # ADD BASE RSC /l 0x809 /d "_DEBUG" # ADD RSC /l 0x809 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept # ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept !ENDIF # Begin Target # Name "luac - Win32 Release" # Name "luac - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=..\lapi.c # End Source File # Begin Source File SOURCE=..\lib\lauxlib.c # End Source File # Begin Source File SOURCE=..\lcode.c # End Source File # Begin Source File SOURCE=..\ldebug.c # End Source File # Begin Source File SOURCE=..\ldo.c # End Source File # Begin Source File SOURCE=..\ldump.c # End Source File # Begin Source File SOURCE=..\lfunc.c # End Source File # Begin Source File SOURCE=..\lgc.c # End Source File # Begin Source File SOURCE=..\llex.c # End Source File # Begin Source File SOURCE=..\lmem.c # End Source File # Begin Source File SOURCE=..\lobject.c # End Source File # Begin Source File SOURCE=..\lopcodes.c # End Source File # Begin Source File SOURCE=..\lparser.c # End Source File # Begin Source File SOURCE=..\lstate.c # End Source File # Begin Source File SOURCE=..\lstring.c # End Source File # Begin Source File SOURCE=..\ltable.c # End Source File # Begin Source File SOURCE=..\ltests.c # End Source File # Begin Source File SOURCE=..\ltm.c # End Source File # Begin Source File SOURCE=.\luac.c # End Source File # Begin Source File SOURCE=..\lundump.c # End Source File # Begin Source File SOURCE=..\lvm.c # End Source File # Begin Source File SOURCE=..\lzio.c # End Source File # Begin Source File SOURCE=.\print.c # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=..\lapi.h # End Source File # Begin Source File SOURCE=..\..\include\lauxlib.h # End Source File # Begin Source File SOURCE=..\lcode.h # End Source File # Begin Source File SOURCE=..\ldebug.h # End Source File # Begin Source File SOURCE=..\ldo.h # End Source File # Begin Source File SOURCE=..\lfunc.h # End Source File # Begin Source File SOURCE=..\LGC.H # End Source File # Begin Source File SOURCE=..\llex.h # End Source File # Begin Source File SOURCE=..\llimits.h # End Source File # Begin Source File SOURCE=..\lmem.h # End Source File # Begin Source File SOURCE=..\lobject.h # End Source File # Begin Source File SOURCE=..\lopcodes.h # End Source File # Begin Source File SOURCE=..\lparser.h # End Source File # Begin Source File SOURCE=..\lstate.h # End Source File # Begin Source File SOURCE=..\lstring.h # End Source File # Begin Source File SOURCE=..\ltable.h # End Source File # Begin Source File SOURCE=..\LTM.H # End Source File # Begin Source File SOURCE=..\..\include\lua.h # End Source File # Begin Source File SOURCE=.\luac.h # End Source File # Begin Source File SOURCE=..\..\include\luadebug.h # End Source File # Begin Source File SOURCE=..\..\include\lualib.h # End Source File # Begin Source File SOURCE=..\lundump.h # End Source File # Begin Source File SOURCE=..\LVM.H # End Source File # Begin Source File SOURCE=..\lzio.h # End Source File # Begin Source File SOURCE=.\print.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project --- NEW FILE: Makefile --- # makefile for Lua compiler LUA= ../.. include $(LUA)/config INCS= -I$(INC) -I.. $(EXTRA_INCS) OBJS= luac.o print.o lopcodes.o SRCS= luac.c print.c T= $(BIN)/luac all: $T $T: $(OBJS) $(LIB)/liblua.a $(LIB)/liblualib.a $(CC) -o $@ $(MYLDFLAGS) $(OBJS) -L$(LIB) -llua -llualib $(EXTRA_LIBS) $(DLLIB) # print.c needs opcode names from lopcodes.c lopcodes.o: ../lopcodes.c ../lopcodes.h $(CC) -o $@ -c $(CFLAGS) -DLUA_OPNAMES ../lopcodes.c $(LIB)/liblua.a: cd ..; $(MAKE) $(LIB)/liblualib.a: cd ../lib; $(MAKE) clean: rm -f $(OBJS) $T co: co -q -f -M $(SRCS) klean: clean rm -f $(SRCS) --- NEW FILE: luac.c --- /* ** $Id: luac.c,v 1.1 2005/06/06 23:06:17 jrl1 Exp $ ** Lua compiler (saves bytecodes to files; also list bytecodes) ** See Copyright Notice in lua.h */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lfunc.h" #include "lmem.h" #include "lobject.h" #include "lopcodes.h" #include "lstring.h" #include "lundump.h" #ifndef LUA_DEBUG #define luaB_opentests(L) #endif #ifndef PROGNAME #define PROGNAME "luac" /* program name */ #endif #define OUTPUT "luac.out" /* default output file */ static int listing=0; /* list bytecodes? */ static int dumping=1; /* dump bytecodes? */ static int stripping=0; /* strip debug information? */ static char Output[]={ OUTPUT }; /* default output file name */ static const char* output=Output; /* output file name */ static const char* progname=PROGNAME; /* actual program name */ static void fatal(const char* message) { fprintf(stderr,"%s: %s\n",progname,message); exit(EXIT_FAILURE); } static void cannot(const char* name, const char* what, const char* mode) { fprintf(stderr,"%s: cannot %s %sput file ",progname,what,mode); perror(name); exit(EXIT_FAILURE); } static void usage(const char* message, const char* arg) { if (message!=NULL) { fprintf(stderr,"%s: ",progname); fprintf(stderr,message,arg); fprintf(stderr,"\n"); } fprintf(stderr, "usage: %s [options] [filenames]. Available options are:\n" " - process stdin\n" " -l list\n" " -o name output to file `name' (default is \"" OUTPUT "\")\n" " -p parse only\n" " -s strip debug information\n" " -v show version information\n" " -- stop handling options\n", progname); exit(EXIT_FAILURE); } #define IS(s) (strcmp(argv[i],s)==0) static int doargs(int argc, char* argv[]) { int i; if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0]; for (i=1; i<argc; i++) { if (*argv[i]!='-') /* end of options; keep it */ break; else if (IS("--")) /* end of options; skip it */ { ++i; break; } else if (IS("-")) /* end of options; use stdin */ return i; else if (IS("-l")) /* list */ listing=1; else if (IS("-o")) /* output file */ { output=argv[++i]; if (output==NULL || *output==0) usage("`-o' needs argument",NULL); } else if (IS("-p")) /* parse only */ dumping=0; else if (IS("-s")) /* strip debug information */ stripping=1; else if (IS("-v")) /* show version */ { printf("%s %s\n",LUA_VERSION,LUA_COPYRIGHT); if (argc==2) exit(EXIT_SUCCESS); } else /* unknown option */ usage("unrecognized option `%s'",argv[i]); } if (i==argc && (listing || !dumping)) { dumping=0; argv[--i]=Output; } return i; } static Proto* toproto(lua_State* L, int i) { const Closure* c=(const Closure*)lua_topointer(L,i); return c->l.p; } static Proto* combine(lua_State* L, int n) { if (n==1) return toproto(L,-1); else { int i,pc=0; Proto* f=luaF_newproto(L); f->source=luaS_newliteral(L,"=(" PROGNAME ")"); f->maxstacksize=1; f->p=luaM_newvector(L,n,Proto*); f->sizep=n; f->sizecode=2*n+1; f->code=luaM_newvector(L,f->sizecode,Instruction); for (i=0; i<n; i++) { f->p[i]=toproto(L,i-n); f->code[pc++]=CREATE_ABx(OP_CLOSURE,0,i); f->code[pc++]=CREATE_ABC(OP_CALL,0,1,1); } f->code[pc++]=CREATE_ABC(OP_RETURN,0,1,0); return f; } } static void strip(lua_State* L, Proto* f) { int i,n=f->sizep; luaM_freearray(L, f->lineinfo, f->sizelineinfo, int); luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar); luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *); f->lineinfo=NULL; f->sizelineinfo=0; f->locvars=NULL; f->sizelocvars=0; f->upvalues=NULL; f->sizeupvalues=0; f->source=luaS_newliteral(L,"=(none)"); for (i=0; i<n; i++) strip(L,f->p[i]); } static int writer(lua_State* L, const void* p, size_t size, void* u) { UNUSED(L); return fwrite(p,size,1,(FILE*)u)==1; } int main(int argc, char* argv[]) { lua_State* L; Proto* f; int i=doargs(argc,argv); argc-=i; argv+=i; if (argc<=0) usage("no input files given",NULL); L=lua_open(); luaB_opentests(L); for (i=0; i<argc; i++) { const char* filename=IS("-") ? NULL : argv[i]; if (luaL_loadfile(L,filename)!=0) fatal(lua_tostring(L,-1)); } f=combine(L,argc); if (listing) luaU_print(f); if (dumping) { FILE* D=fopen(output,"wb"); if (D==NULL) cannot(output,"open","out"); if (stripping) strip(L,f); lua_lock(L); luaU_dump(L,f,writer,D); lua_unlock(L); if (ferror(D)) cannot(output,"write","out"); fclose(D); } lua_close(L); return 0; } --- NEW FILE: print.c --- /* ** $Id: print.c,v 1.1 2005/06/06 23:06:17 jrl1 Exp $ ** print bytecodes ** See Copyright Notice in lua.h */ #include <stdio.h> #if 0 #define DEBUG_PRINT #endif #ifndef LUA_OPNAMES #define LUA_OPNAMES #endif #include "ldebug.h" #include "lobject.h" #include "lopcodes.h" #include "lundump.h" #define Sizeof(x) ((int)sizeof(x)) #define VOID(p) ((const void*)(p)) static void PrintString(const Proto* f, int n) { const char* s=svalue(&f->k[n]); putchar('"'); for (; *s; s++) { switch (*s) { case '"': printf("\\\""); break; case '\a': printf("\\a"); break; case '\b': printf("\\b"); break; case '\f': printf("\\f"); break; case '\n': printf("\\n"); break; case '\r': printf("\\r"); break; case '\t': printf("\\t"); break; case '\v': printf("\\v"); break; default: putchar(*s); break; } } putchar('"'); } static void PrintConstant(const Proto* f, int i) { const TObject* o=&f->k[i]; switch (ttype(o)) { case LUA_TNUMBER: printf(LUA_NUMBER_FMT,nvalue(o)); break; case LUA_TSTRING: PrintString(f,i); break; case LUA_TNIL: printf("nil"); break; default: /* cannot happen */ printf("? type=%d",ttype(o)); break; } } static void PrintCode(const Proto* f) { const Instruction* code=f->code; int pc,n=f->sizecode; for (pc=0; pc<n; pc++) { Instruction i=code[pc]; OpCode o=GET_OPCODE(i); int a=GETARG_A(i); int b=GETARG_B(i); int c=GETARG_C(i); int bc=GETARG_Bx(i); int sbc=GETARG_sBx(i); int line=getline(f,pc); #if 0 printf("%0*lX",Sizeof(i)*2,i); #endif printf("\t%d\t",pc+1); if (line>0) printf("[%d]\t",line); else printf("[-]\t"); printf("%-9s\t",luaP_opnames[o]); switch (getOpMode(o)) { case iABC: printf("%d %d %d",a,b,c); break; case iABx: printf("%d %d",a,bc); break; case iAsBx: printf("%d %d",a,sbc); break; } switch (o) { case OP_LOADK: printf("\t; "); PrintConstant(f,bc); break; case OP_GETUPVAL: case OP_SETUPVAL: printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b]) : "-"); break; case OP_GETGLOBAL: case OP_SETGLOBAL: printf("\t; %s",svalue(&f->k[bc])); break; case OP_GETTABLE: case OP_SELF: if (c>=MAXSTACK) { printf("\t; "); PrintConstant(f,c-MAXSTACK); } break; case OP_SETTABLE: case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_POW: case OP_EQ: case OP_LT: case OP_LE: if (b>=MAXSTACK || c>=MAXSTACK) { printf("\t; "); if (b>=MAXSTACK) PrintConstant(f,b-MAXSTACK); else printf("-"); printf(" "); if (c>=MAXSTACK) PrintConstant(f,c-MAXSTACK); } break; case OP_JMP: case OP_FORLOOP: case OP_TFORPREP: printf("\t; to %d",sbc+pc+2); break; case OP_CLOSURE: printf("\t; %p",VOID(f->p[bc])); break; default: break; } printf("\n"); } } static const char* Source(const Proto* f) { const char* s=getstr(f->source); if (*s=='@' || *s=='=') return s+1; else if (*s==LUA_SIGNATURE[0]) return "(bstring)"; else return "(string)"; } #define IsMain(f) (f->lineDefined==0) #define SS(x) (x==1)?"":"s" #define S(x) x,SS(x) static void PrintHeader(const Proto* f) { printf("\n%s <%s:%d> (%d instruction%s, %d bytes at %p)\n", IsMain(f)?"main":"function",Source(f),f->lineDefined, S(f->sizecode),f->sizecode*Sizeof(Instruction),VOID(f)); printf("%d%s param%s, %d stack%s, %d upvalue%s, ", f->numparams,f->is_vararg?"+":"",SS(f->numparams),S(f->maxstacksize), S(f->nups)); printf("%d local%s, %d constant%s, %d function%s\n", S(f->sizelocvars),S(f->sizek),S(f->sizep)); } #ifdef DEBUG_PRINT static void PrintConstants(const Proto* f) { int i,n=f->sizek; printf("constants (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t",i); PrintConstant(f,i); printf("\n"); } } static void PrintLocals(const Proto* f) { int i,n=f->sizelocvars; printf("locals (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t%s\t%d\t%d\n", i,getstr(f->locvars[i].varname),f->locvars[i].startpc,f->locvars[i].endpc); } } static void PrintUpvalues(const Proto* f) { int i,n=f->sizeupvalues; printf("upvalues (%d) for %p:\n",n,VOID(f)); if (f->upvalues==NULL) return; for (i=0; i<n; i++) { printf("\t%d\t%s\n",i,getstr(f->upvalues[i])); } } #endif void luaU_print(const Proto* f) { int i,n=f->sizep; PrintHeader(f); PrintCode(f); #ifdef DEBUG_PRINT PrintConstants(f); PrintLocals(f); PrintUpvalues(f); #endif for (i=0; i<n; i++) luaU_print(f->p[i]); } |
From: John L. <jr...@us...> - 2005-06-06 23:06:27
|
Update of /cvsroot/wxlua/wxLua/modules/lua/src/lua In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/src/lua Added Files: Makefile README lua.c lua.dsp Log Message: moved files to the modules directory structure --- NEW FILE: README --- This is lua, a sample Lua interpreter. It can be used as a batch interpreter and also interactively. There are man pages for it in both nroff and html in ../../doc. Usage: ./lua [options] [script [args]]. Available options are: - execute stdin as a file -e stat execute string `stat' -i enter interactive mode after executing `script' -l name load and run library `name' -v show version information -- stop handling options This interpreter is suitable for using Lua as a standalone language; it loads all standard libraries. For a minimal interpreter, see ../../etc/min.c. If your application simply exports new functions to Lua (which is common), then you can use this interpreter (almost) unmodified, as follows: * First, define a function void myinit (lua_State *L) in your own code. In this function, you should do whatever initializations are needed by your application, typically exporting your functions to Lua. (Of course, you can use any name instead of "myinit".) * Then, #define lua_userinit(L) to be "openstdlibs(L)+myinit(L)". Here, openstdlibs is a function in lua.c that opens all standard libraries. If you don't need them, just don't call openstdlibs and open any standard libraries that you do need in myinit. * Finally, remember to link your C code when building lua. For other customizations, see ../../etc/config.c. --- NEW FILE: lua.dsp --- # Microsoft Developer Studio Project File - Name="lua" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=lua - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "lua.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "lua.mak" CFG="lua - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "lua - Win32 Release" (based on "Win32 (x86) Console Application") !MESSAGE "lua - Win32 Debug" (based on "Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "lua - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /FdRelease\lua.pdb /c # ADD CPP /nologo /MD /W4 /GX /O2 /I "..\..\include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /FdRelease\lua.pdb /c # ADD BASE RSC /l 0x809 /d "NDEBUG" # ADD RSC /l 0x809 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 /nologo /subsystem:console /machine:I386 /out:"..\..\..\bin\lua.exe" # ADD LINK32 /nologo /subsystem:console /machine:I386 /out:"..\..\..\bin\lua.exe" !ELSEIF "$(CFG)" == "lua - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /FdDebug\luad.pdb /c # ADD CPP /nologo /MDd /W4 /Gm /GX /ZI /Od /I "..\..\include" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /FdDebug\luad.pdb /c # ADD BASE RSC /l 0x809 /d "_DEBUG" # ADD RSC /l 0x809 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /out:"..\..\..\bin\luad.exe" # ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /out:"..\..\..\bin\luad.exe" !ENDIF # Begin Target # Name "lua - Win32 Release" # Name "lua - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\lua.c # End Source File # Begin Source File SOURCE=..\LAPI.C # End Source File # Begin Source File SOURCE=..\LAPI.H # End Source File # Begin Source File SOURCE=..\LIB\LAUXLIB.C # End Source File # Begin Source File SOURCE=..\LIB\LBASELIB.C # End Source File # Begin Source File SOURCE=..\LCODE.C # End Source File # Begin Source File SOURCE=..\LCODE.H # End Source File # Begin Source File SOURCE=..\LIB\LDBLIB.C # End Source File # Begin Source File SOURCE=..\LDEBUG.C # End Source File # Begin Source File SOURCE=..\LDEBUG.H # End Source File # Begin Source File SOURCE=..\LDLLMAIN.C # End Source File # Begin Source File SOURCE=..\LDO.C # End Source File # Begin Source File SOURCE=..\LDO.H # End Source File # Begin Source File SOURCE=..\ldump.c # End Source File # Begin Source File SOURCE=..\LFUNC.C # End Source File # Begin Source File SOURCE=..\LFUNC.H # End Source File # Begin Source File SOURCE=..\LGC.C # End Source File # Begin Source File SOURCE=..\LGC.H # End Source File # Begin Source File SOURCE=..\LIB\LIOLIB.C # End Source File # Begin Source File SOURCE=..\LLEX.C # End Source File # Begin Source File SOURCE=..\LLEX.H # End Source File # Begin Source File SOURCE=..\LLIMITS.H # End Source File # Begin Source File SOURCE=..\LIB\LMATHLIB.C # End Source File # Begin Source File SOURCE=..\LMEM.C # End Source File # Begin Source File SOURCE=..\LMEM.H # End Source File # Begin Source File SOURCE=..\lib\loadlib.c # End Source File # Begin Source File SOURCE=..\LOBJECT.C # End Source File # Begin Source File SOURCE=..\LOBJECT.H # End Source File # Begin Source File SOURCE=..\LOPCODES.C # End Source File # Begin Source File SOURCE=..\LOPCODES.H # End Source File # Begin Source File SOURCE=..\LPARSER.C # End Source File # Begin Source File SOURCE=..\LPARSER.H # End Source File # Begin Source File SOURCE=..\..\lslua50m.def # End Source File # Begin Source File SOURCE=..\LSTATE.C # End Source File # Begin Source File SOURCE=..\LSTATE.H # End Source File # Begin Source File SOURCE=..\LSTRING.C # End Source File # Begin Source File SOURCE=..\LSTRING.H # End Source File # Begin Source File SOURCE=..\LIB\LSTRLIB.C # End Source File # Begin Source File SOURCE=..\LTABLE.C # End Source File # Begin Source File SOURCE=..\LTABLE.H # End Source File # Begin Source File SOURCE=..\lib\ltablib.c # End Source File # Begin Source File SOURCE=..\LTESTS.C # End Source File # Begin Source File SOURCE=..\LTM.C # End Source File # Begin Source File SOURCE=..\LTM.H # End Source File # Begin Source File SOURCE=..\LUNDUMP.C # End Source File # Begin Source File SOURCE=..\LUNDUMP.H # End Source File # Begin Source File SOURCE=..\LVM.C # End Source File # Begin Source File SOURCE=..\LVM.H # End Source File # Begin Source File SOURCE=..\LZIO.C # End Source File # Begin Source File SOURCE=..\LZIO.H # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=..\..\include\ldlgdyn.h # End Source File # Begin Source File SOURCE=..\..\include\lua.h # End Source File # Begin Source File SOURCE=..\..\include\luadebug.h # End Source File # Begin Source File SOURCE=..\..\include\lualib.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # Begin Group "Lua Test files" # PROP Default_Filter "" # Begin Source File SOURCE=..\..\test\arraysample.lua # End Source File # Begin Source File SOURCE=..\..\test\bisect.lua # End Source File # Begin Source File SOURCE=..\..\test\bug18102000.lua # End Source File # Begin Source File SOURCE="..\..\test\cf-for.lua" # End Source File # Begin Source File SOURCE=..\..\test\cf.lua # End Source File # Begin Source File SOURCE=..\..\test\factorial.lua # End Source File # Begin Source File SOURCE=..\..\test\fib.lua # End Source File # Begin Source File SOURCE=..\..\test\globals.lua # End Source File # Begin Source File SOURCE=..\..\test\hello.lua # End Source File # Begin Source File SOURCE=..\..\test\life.lua # End Source File # Begin Source File SOURCE=..\..\test\lisp.lua # End Source File # Begin Source File SOURCE=..\..\test\old.lua # End Source File # Begin Source File SOURCE=..\..\test\qp.lua # End Source File # Begin Source File SOURCE=..\..\test\save.lua # End Source File # Begin Source File SOURCE=..\..\test\sort.lua # End Source File # Begin Source File SOURCE=..\..\test\table.lua # End Source File # Begin Source File SOURCE=..\..\test\test.lua # End Source File # Begin Source File SOURCE=..\..\test\test7.lua # End Source File # Begin Source File SOURCE=..\..\test\test7sub.lua # End Source File # Begin Source File SOURCE=..\..\test\test8.lua # End Source File # Begin Source File SOURCE="..\..\test\trace-calls.lua" # End Source File # Begin Source File SOURCE="..\..\test\trace-globals.lua" # End Source File # Begin Source File SOURCE=..\..\test\undefined.lua # End Source File # Begin Source File SOURCE=..\..\test\webform.lua # End Source File # End Group # End Target # End Project --- NEW FILE: Makefile --- # makefile for Lua interpreter LUA= ../.. include $(LUA)/config EXTRA_DEFS= $(USERCONF) OBJS= lua.o SRCS= lua.c T= $(BIN)/lua all: $T $T: $(OBJS) $(LIB)/liblua.a $(LIB)/liblualib.a $(CC) -o $@ $(MYLDFLAGS) $(OBJS) -L$(LIB) -llua -llualib $(EXTRA_LIBS) $(DLLIB) $(LIB)/liblua.a: cd ..; $(MAKE) $(LIB)/liblualib.a: cd ../lib; $(MAKE) clean: rm -f $(OBJS) $T co: co -q -f -M $(SRCS) klean: clean rm -f $(SRCS) --- NEW FILE: lua.c --- /* ** $Id: lua.c,v 1.1 2005/06/06 23:06:17 jrl1 Exp $ ** Lua stand-alone interpreter ** See Copyright Notice in lua.h */ #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define lua_c #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** generic extra include file */ #ifdef LUA_USERCONFIG #include LUA_USERCONFIG #endif /* ** definition of `isatty' */ #ifdef _POSIX_C_SOURCE #include <unistd.h> #define stdin_is_tty() isatty(0) #else #define stdin_is_tty() 1 /* assume stdin is a tty */ #endif #ifndef PROMPT #define PROMPT "> " #endif #ifndef PROMPT2 #define PROMPT2 ">> " #endif #ifndef PROGNAME #define PROGNAME "lua" #endif #ifndef lua_userinit #define lua_userinit(L) openstdlibs(L) #endif #ifndef LUA_EXTRALIBS #define LUA_EXTRALIBS /* empty */ #endif static lua_State *L = NULL; static const char *progname = PROGNAME; static const luaL_reg lualibs[] = { {"base", luaopen_base}, {"table", luaopen_table}, {"io", luaopen_io}, {"string", luaopen_string}, {"math", luaopen_math}, {"debug", luaopen_debug}, {"loadlib", luaopen_loadlib}, /* add your libraries here */ LUA_EXTRALIBS {NULL, NULL} }; static void lstop (lua_State *l, lua_Debug *ar) { (void)ar; /* unused arg. */ lua_sethook(l, NULL, 0, 0); luaL_error(l, "interrupted!"); } static void laction (int i) { signal(i, SIG_DFL); /* if another SIGINT happens before lstop, terminate process (default action) */ lua_sethook(L, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); } static void print_usage (void) { fprintf(stderr, "usage: %s [options] [script [args]].\n" "Available options are:\n" " - execute stdin as a file\n" " -e stat execute string `stat'\n" " -i enter interactive mode after executing `script'\n" " -l name load and run library `name'\n" " -v show version information\n" " -- stop handling options\n" , progname); } static void l_message (const char *pname, const char *msg) { if (pname) fprintf(stderr, "%s: ", pname); fprintf(stderr, "%s\n", msg); } static int report (int status) { const char *msg; if (status) { msg = lua_tostring(L, -1); if (msg == NULL) msg = "(error with no message)"; l_message(progname, msg); lua_pop(L, 1); } return status; } static int lcall (int narg, int clear) { int status; int base = lua_gettop(L) - narg; /* function index */ lua_pushliteral(L, "_TRACEBACK"); lua_rawget(L, LUA_GLOBALSINDEX); /* get traceback function */ lua_insert(L, base); /* put it under chunk and args */ signal(SIGINT, laction); status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); signal(SIGINT, SIG_DFL); lua_remove(L, base); /* remove traceback function */ return status; } static void print_version (void) { l_message(NULL, LUA_VERSION " " LUA_COPYRIGHT); } static void getargs (char *argv[], int n) { int i; lua_newtable(L); for (i=0; argv[i]; i++) { lua_pushnumber(L, i - n); lua_pushstring(L, argv[i]); lua_rawset(L, -3); } /* arg.n = maximum index in table `arg' */ lua_pushliteral(L, "n"); lua_pushnumber(L, i-n-1); lua_rawset(L, -3); } static int docall (int status) { if (status == 0) status = lcall(0, 1); return report(status); } static int file_input (const char *name) { return docall(luaL_loadfile(L, name)); } static int dostring (const char *s, const char *name) { return docall(luaL_loadbuffer(L, s, strlen(s), name)); } static int load_file (const char *name) { lua_pushliteral(L, "require"); lua_rawget(L, LUA_GLOBALSINDEX); if (!lua_isfunction(L, -1)) { /* no `require' defined? */ lua_pop(L, 1); return file_input(name); } else { lua_pushstring(L, name); return report(lcall(1, 1)); } } /* ** this macro can be used by some `history' system to save lines ** read in manual input */ #ifndef lua_saveline #define lua_saveline(L,line) /* empty */ #endif /* ** this macro defines a function to show the prompt and reads the ** next line for manual input */ #ifndef lua_readline #define lua_readline(L,prompt) readline(L,prompt) /* maximum length of an input line */ #ifndef MAXINPUT #define MAXINPUT 512 #endif static int readline (lua_State *l, const char *prompt) { static char buffer[MAXINPUT]; if (prompt) { fputs(prompt, stdout); fflush(stdout); } if (fgets(buffer, sizeof(buffer), stdin) == NULL) return 0; /* read fails */ else { lua_pushstring(l, buffer); return 1; } } #endif static const char *get_prompt (int firstline) { const char *p = NULL; lua_pushstring(L, firstline ? "_PROMPT" : "_PROMPT2"); lua_rawget(L, LUA_GLOBALSINDEX); p = lua_tostring(L, -1); if (p == NULL) p = (firstline ? PROMPT : PROMPT2); lua_pop(L, 1); /* remove global */ return p; } static int incomplete (int status) { if (status == LUA_ERRSYNTAX && strstr(lua_tostring(L, -1), "near `<eof>'") != NULL) { lua_pop(L, 1); return 1; } else return 0; } static int load_string (void) { int status; lua_settop(L, 0); if (lua_readline(L, get_prompt(1)) == 0) /* no input? */ return -1; if (lua_tostring(L, -1)[0] == '=') { /* line starts with `=' ? */ lua_pushfstring(L, "return %s", lua_tostring(L, -1)+1);/* `=' -> `return' */ lua_remove(L, -2); /* remove original line */ } for (;;) { /* repeat until gets a complete line */ status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); if (!incomplete(status)) break; /* cannot try to add lines? */ if (lua_readline(L, get_prompt(0)) == 0) /* no more input? */ return -1; lua_concat(L, lua_gettop(L)); /* join lines */ } lua_saveline(L, lua_tostring(L, 1)); lua_remove(L, 1); /* remove line */ return status; } static void manual_input (void) { int status; const char *oldprogname = progname; progname = NULL; while ((status = load_string()) != -1) { if (status == 0) status = lcall(0, 0); report(status); if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */ lua_getglobal(L, "print"); lua_insert(L, 1); if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) l_message(progname, lua_pushfstring(L, "error calling `print' (%s)", lua_tostring(L, -1))); } } lua_settop(L, 0); /* clear stack */ fputs("\n", stdout); progname = oldprogname; } static int handle_argv (char *argv[], int *interactive) { if (argv[1] == NULL) { /* no more arguments? */ if (stdin_is_tty()) { print_version(); manual_input(); } else file_input(NULL); /* executes stdin as a file */ } else { /* other arguments; loop over them */ int i; for (i = 1; argv[i] != NULL; i++) { if (argv[i][0] != '-') break; /* not an option? */ switch (argv[i][1]) { /* option */ case '-': { /* `--' */ if (argv[i][2] != '\0') { print_usage(); return 1; } i++; /* skip this argument */ goto endloop; /* stop handling arguments */ } case '\0': { file_input(NULL); /* executes stdin as a file */ break; } case 'i': { *interactive = 1; break; } case 'v': { print_version(); break; } case 'e': { const char *chunk = argv[i] + 2; if (*chunk == '\0') chunk = argv[++i]; if (chunk == NULL) { print_usage(); return 1; } if (dostring(chunk, "=<command line>") != 0) return 1; break; } case 'l': { const char *filename = argv[i] + 2; if (*filename == '\0') filename = argv[++i]; if (filename == NULL) { print_usage(); return 1; } if (load_file(filename)) return 1; /* stop if file fails */ break; } case 'c': { l_message(progname, "option `-c' is deprecated"); break; } case 's': { l_message(progname, "option `-s' is deprecated"); break; } default: { print_usage(); return 1; } } } endloop: if (argv[i] != NULL) { const char *filename = argv[i]; getargs(argv, i); /* collect arguments */ lua_setglobal(L, "arg"); return file_input(filename); /* stop scanning arguments */ } } return 0; } static void openstdlibs (lua_State *l) { const luaL_reg *lib = lualibs; for (; lib->func; lib++) { lib->func(l); /* open library */ lua_settop(l, 0); /* discard any results */ } } static int handle_luainit (void) { const char *init = getenv("LUA_INIT"); if (init == NULL) return 0; /* status OK */ else if (init[0] == '@') return file_input(init+1); else return dostring(init, "=LUA_INIT"); } struct Smain { int argc; char **argv; int status; }; static int pmain (lua_State *l) { struct Smain *s = (struct Smain *)lua_touserdata(l, 1); int status; int interactive = 0; if (s->argv[0] && s->argv[0][0]) progname = s->argv[0]; L = l; lua_userinit(l); /* open libraries */ status = handle_luainit(); if (status == 0) { status = handle_argv(s->argv, &interactive); if (status == 0 && interactive) manual_input(); } s->status = status; return 0; } int main (int argc, char *argv[]) { int status; struct Smain s; lua_State *l = lua_open(); /* create state */ if (l == NULL) { l_message(argv[0], "cannot create state: not enough memory"); return EXIT_FAILURE; } s.argc = argc; s.argv = argv; status = lua_cpcall(l, &pmain, &s); report(status); lua_close(l); return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS; } |
From: John L. <jr...@us...> - 2005-06-06 23:06:27
|
Update of /cvsroot/wxlua/wxLua/modules/lua/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/doc Added Files: contents.html logo.gif lua.1 lua.html luac.1 luac.html manual.html readme.html Log Message: moved files to the modules directory structure --- NEW FILE: luac.html --- <!-- luac.man,v 1.25 2002/12/13 11:45:12 lhf Exp --> <HTML> <HEAD> <TITLE>LUAC man page</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <H1>NAME</H1> luac - Lua compiler <H1>SYNOPSIS</H1> <B>luac</B> [ <I>options</I> ] [ <I>filenames</I> ] <H1>DESCRIPTION</H1> <B>luac</B> is the Lua compiler. It translates programs written in the Lua programming language into binary files that can be latter loaded and executed. <P> The main advantages of precompiling chunks are: faster loading, protecting source code from user changes, and off-line syntax checking. <P> Pre-compiling does not imply faster execution because in Lua chunks are always compiled into bytecodes before being executed. <B>luac</B> simply allows those bytecodes to be saved in a file for later execution. <P> <B>luac</B> produces a single output file containing the bytecodes for all source files given. By default, the output file is named <B>luac.out</B>, but you can change this with the <B>-o</B> option. <P> The binary files created by <B>luac</B> are portable to all architectures with the same word size. This means that binary files created on a 32-bit platform (such as Intel) can be read without change in another 32-bit platform (such as Sparc), even if the byte order (``endianness'') is different. On the other hand, binary files created on a 16-bit platform cannot be read in a 32-bit platform, nor vice-versa. <P> In the command line, you can mix text files containing Lua source and binary files containing precompiled chunks. This is useful to combine several precompiled chunks, even from different (but compatible) platforms, into a single precompiled chunk. <P> You can use <B>"-"</B> to indicate the standard input as a source file and <B>"--"</B> to signal the end of options (that is, all remaining arguments will be treated as files even if they start with <B>"-"</B>). <P> The internal format of the binary files produced by <B>luac</B> is likely to change when a new version of Lua is released. So, save the source files of all Lua programs that you precompile. <P> <H1>OPTIONS</H1> Options must be separate. <P> <B>-l</B> produce a listing of the compiled bytecode for Lua's virtual machine. Listing bytecodes is useful to learn about Lua's virtual machine. If no files are given, then <B>luac</B> loads <B>luac.out</B> and lists its contents. <P> <B>-o "</B><I>file"</I> output to <I>file</I>, instead of the default <B>luac.out</B>. The output file may be a source file because all files are loaded before the output file is written. Be careful not to overwrite precious files. <P> <B>-p</B> load files but do not generate any output file. Used mainly for syntax checking and for testing precompiled chunks: corrupted files will probably generate errors when loaded. Lua always performs a thorough integrity test on precompiled chunks. Bytecode that passes this test is completely safe, in the sense that it will not break the interpreter. However, there is no guarantee that such code does anything sensible. (None can be given, because the halting problem is unsolvable.) If no files are given, then <B>luac</B> loads <B>luac.out</B> and tests its contents. No messages are displayed if the file passes the integrity test. <P> <B>-s</B> strip debug information before writing the output file. This saves some space in very large chunks, but if errors occur when running these chunks, then the error messages may not contain the full information they usually do (line numbers and names of locals are lost). <P> <B>-v</B> show version information. <H1>FILES</H1> <P> <B>luac.out</B> default output file <H1>SEE ALSO</H1> <B>lua</B>(1) <BR> <A HREF="http://www.lua.org/">http://www.lua.org/</A> <H1>DIAGNOSTICS</H1> Error messages should be self explanatory. <H1>AUTHORS</H1> L. H. de Figueiredo, R. Ierusalimschy and W. Celes (<A HREF="mailto:lua...@te...">lua AT tecgraf.puc-rio.br</A>) <!-- EOF --> </BODY> </HTML> --- NEW FILE: luac.1 --- .\" luac.man,v 1.25 2002/12/13 11:45:12 lhf Exp .TH LUAC 1 "2002/12/13 11:45:12" .SH NAME luac \- Lua compiler .SH SYNOPSIS .B luac [ .I options ] [ .I filenames ] .SH DESCRIPTION .B luac is the Lua compiler. It translates programs written in the Lua programming language into binary files that can be latter loaded and executed. .LP The main advantages of precompiling chunks are: faster loading, protecting source code from user changes, and off-line syntax checking. .LP Pre-compiling does not imply faster execution because in Lua chunks are always compiled into bytecodes before being executed. .B luac simply allows those bytecodes to be saved in a file for later execution. .LP .B luac produces a single output file containing the bytecodes for all source files given. By default, the output file is named .BR luac.out , but you can change this with the .B \-o option. .LP The binary files created by .B luac are portable to all architectures with the same word size. This means that binary files created on a 32-bit platform (such as Intel) can be read without change in another 32-bit platform (such as Sparc), even if the byte order (``endianness'') is different. On the other hand, binary files created on a 16-bit platform cannot be read in a 32-bit platform, nor vice-versa. .LP In the command line, you can mix text files containing Lua source and binary files containing precompiled chunks. This is useful to combine several precompiled chunks, even from different (but compatible) platforms, into a single precompiled chunk. .LP You can use .B "\-" to indicate the standard input as a source file and .B "\--" to signal the end of options (that is, all remaining arguments will be treated as files even if they start with .BR "\-" ). .LP The internal format of the binary files produced by .B luac is likely to change when a new version of Lua is released. So, save the source files of all Lua programs that you precompile. .LP .SH OPTIONS Options must be separate. .TP .B \-l produce a listing of the compiled bytecode for Lua's virtual machine. Listing bytecodes is useful to learn about Lua's virtual machine. If no files are given, then .B luac loads .B luac.out and lists its contents. .TP .BI \-o " file" output to .IR file , instead of the default .BR luac.out . The output file may be a source file because all files are loaded before the output file is written. Be careful not to overwrite precious files. .TP .B \-p load files but do not generate any output file. Used mainly for syntax checking and for testing precompiled chunks: corrupted files will probably generate errors when loaded. Lua always performs a thorough integrity test on precompiled chunks. Bytecode that passes this test is completely safe, in the sense that it will not break the interpreter. However, there is no guarantee that such code does anything sensible. (None can be given, because the halting problem is unsolvable.) If no files are given, then .B luac loads .B luac.out and tests its contents. No messages are displayed if the file passes the integrity test. .TP .B \-s strip debug information before writing the output file. This saves some space in very large chunks, but if errors occur when running these chunks, then the error messages may not contain the full information they usually do (line numbers and names of locals are lost). .TP .B \-v show version information. .SH FILES .TP 15 .B luac.out default output file .SH "SEE ALSO" .BR lua (1) .br http://www.lua.org/ .SH DIAGNOSTICS Error messages should be self explanatory. .SH AUTHORS L. H. de Figueiredo, R. Ierusalimschy and W. Celes (lu...@te...) .\" EOF --- NEW FILE: contents.html --- <HTML> <HEAD> <TITLE>Lua: 5.0 reference manual - contents</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <HR> <H1> <A HREF="http://www.lua.org/home.html"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A> Reference manual for Lua 5.0 </H1> <A HREF="manual.html">Lua 5.0 Reference Manual</A> [ <A HREF="manual.html">top</A> | <A HREF="http://www.lua.org/ftp/refman-5.0.ps.gz">ps</A> | <A HREF="http://www.lua.org/ftp/refman-5.0.pdf">pdf</A> ] <P> <SMALL> <A HREF="http://www.lua.org/copyright.html">Copyright</A> © 2003 Tecgraf, PUC-Rio. All rights reserved.</SMALL> <HR> <UL> <LI><A HREF="manual.html#1">1 - Introduction</A> <LI><A HREF="manual.html#2">2 - The Language</A> <UL> <LI><A HREF="manual.html#2.1">2.1 - Lexical Conventions</A> <LI><A HREF="manual.html#2.2">2.2 - Values and Types</A> <UL> <LI><A HREF="manual.html#2.2.1">2.2.1 - Coercion</A> </UL> <LI><A HREF="manual.html#2.3">2.3 - Variables</A> <LI><A HREF="manual.html#2.4">2.4 - Statements</A> <UL> <LI><A HREF="manual.html#2.4.1">2.4.1 - Chunks</A> <LI><A HREF="manual.html#2.4.2">2.4.2 - Blocks</A> <LI><A HREF="manual.html#2.4.3">2.4.3 - Assignment</A> <LI><A HREF="manual.html#2.4.4">2.4.4 - Control Structures</A> <LI><A HREF="manual.html#2.4.5">2.4.5 - For Statement</A> <LI><A HREF="manual.html#2.4.6">2.4.6 - Function Calls as Statements</A> <LI><A HREF="manual.html#2.4.7">2.4.7 - Local Declarations</A> </UL> <LI><A HREF="manual.html#2.5">2.5 - Expressions</A> <UL> <LI><A HREF="manual.html#2.5.1">2.5.1 - Arithmetic Operators</A> <LI><A HREF="manual.html#2.5.2">2.5.2 - Relational Operators</A> <LI><A HREF="manual.html#2.5.3">2.5.3 - Logical Operators</A> <LI><A HREF="manual.html#2.5.4">2.5.4 - Concatenation</A> <LI><A HREF="manual.html#2.5.5">2.5.5 - Precedence</A> <LI><A HREF="manual.html#2.5.6">2.5.6 - Table Constructors</A> <LI><A HREF="manual.html#2.5.7">2.5.7 - Function Calls</A> <LI><A HREF="manual.html#2.5.8">2.5.8 - Function Definitions</A> </UL> </UL> <UL> <LI><A HREF="manual.html#2.6">2.6 - Visibility Rules</A> <LI><A HREF="manual.html#2.7">2.7 - Error Handling</A> <LI><A HREF="manual.html#2.8">2.8 - Metatables</A> <LI><A HREF="manual.html#2.9">2.9 - Garbage Collection</A> <UL> <LI><A HREF="manual.html#2.9.1">2.9.1 - Garbage-Collection Metamethods</A> <LI><A HREF="manual.html#2.9.2">2.9.2 - Weak Tables</A> </UL> <LI><A HREF="manual.html#2.10">2.10 - Coroutines</A> </UL> <LI><A HREF="manual.html#3">3 - The Application Program Interface</A> <UL> <LI><A HREF="manual.html#3.1">3.1 - States</A> <LI><A HREF="manual.html#3.2">3.2 - The Stack and Indices</A> <LI><A HREF="manual.html#3.3">3.3 - Stack Manipulation</A> <LI><A HREF="manual.html#3.4">3.4 - Querying the Stack</A> <LI><A HREF="manual.html#3.5">3.5 - Getting Values from the Stack</A> <LI><A HREF="manual.html#3.6">3.6 - Pushing Values onto the Stack</A> <LI><A HREF="manual.html#3.7">3.7 - Controlling Garbage Collection</A> <LI><A HREF="manual.html#3.8">3.8 - Userdata</A> <LI><A HREF="manual.html#3.9">3.9 - Metatables</A> <LI><A HREF="manual.html#3.10">3.10 - Loading Lua Chunks</A> <LI><A HREF="manual.html#3.11">3.11 - Manipulating Tables</A> <LI><A HREF="manual.html#3.12">3.12 - Manipulating Environments</A> <LI><A HREF="manual.html#3.13">3.13 - Using Tables as Arrays</A> <LI><A HREF="manual.html#3.14">3.14 - Calling Functions</A> <LI><A HREF="manual.html#3.15">3.15 - Protected Calls</A> <LI><A HREF="manual.html#3.16">3.16 - Defining C Functions</A> <LI><A HREF="manual.html#3.17">3.17 - Defining C Closures</A> <LI><A HREF="manual.html#3.18">3.18 - Registry</A> <LI><A HREF="manual.html#3.19">3.19 - Error Handling in C</A> <LI><A HREF="manual.html#3.20">3.20 - Threads</A> </UL> <LI><A HREF="manual.html#4">4 - The Debug Interface</A> <UL> <LI><A HREF="manual.html#4.1">4.1 - Stack and Function Information</A> <LI><A HREF="manual.html#4.2">4.2 - Manipulating Local Variables and Upvalues</A> <LI><A HREF="manual.html#4.3">4.3 - Hooks</A> </UL> <LI><A HREF="manual.html#5">5 - Standard Libraries</A> <UL> <LI><A HREF="manual.html#5.1">5.1 - Basic Functions</A> <LI><A HREF="manual.html#5.2">5.2 - Coroutine Manipulation</A> <LI><A HREF="manual.html#5.3">5.3 - String Manipulation</A> <LI><A HREF="manual.html#5.4">5.4 - Table Manipulation</A> <LI><A HREF="manual.html#5.5">5.5 - Mathematical Functions</A> <LI><A HREF="manual.html#5.6">5.6 - Input and Output Facilities</A> <LI><A HREF="manual.html#5.7">5.7 - Operating System Facilities</A> <LI><A HREF="manual.html#5.8">5.8 - The Reflexive Debug Interface</A> </UL> <LI><A HREF="manual.html#6">6 - Lua Stand-alone</A> <LI><A HREF="manual.html#BNF">The Complete Syntax of Lua</A> </UL> <HR> <SMALL> Last update: Wed May 7 18:34:34 EST 2003 </SMALL> </BODY> </HTML> --- NEW FILE: lua.html --- <!-- lua.man,v 1.8 2003/04/02 00:05:20 lhf Exp --> <HTML> <HEAD> <TITLE>LUA man page</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <H1>NAME</H1> lua - Lua interpreter <H1>SYNOPSIS</H1> <B>lua</B> [ <I>options</I> ] [ <I>script</I> [ <I>args</I> ] ] <H1>DESCRIPTION</H1> <B>lua</B> is the stand-alone Lua interpreter. It loads and executes Lua programs, either in textual source form or in precompiled binary form. (Precompiled binaries are output by <B>luac</B>, the Lua compiler.) <B>lua</B> can be used as a batch interpreter and also interactively. <P> The given <I>options</I> (see below) are executed and then the Lua program in file <I>script</I> is loaded and executed. The given <I>args</I> are available to <I>script</I> as strings in a global table named <B>arg</B>. If these arguments contain spaces or other characters special to the shell, then they should be quoted (but note that the quotes will be removed by the shell). The arguments in <B>arg</B> start at 0, which contains the string `<I>script</I>'. The index of the last argument is stored in <B>"arg.n"</B>. The arguments given in the command line before <I>script</I>, including the name of the interpreter, are available in negative indices in <B>arg</B>. <P> At the very start, before even handling the command line, <B>lua</B> executes the contents of the environment variable <B>LUA_INIT</B>, if it is defined. If the value of <B>LUA_INIT</B> is of the form `@<I>filename</I>', then <I>filename</I> is executed. Otherwise, the string is assumed to be a Lua statement and is executed. <P> Options start with <B>-</B> and are described below. You can use <B>"--"</B> to signal the end of options. <P> If no arguments are given, then <B>"-v -i"</B> is assumed when the standard input is a terminal; otherwise, <B>"-"</B> is assumed. <P> In interactive mode, <B>lua</B> prompts the user, reads lines from the standard input, and executes them as they are read. If a line does not contain a complete statement, then a secondary prompt is displayed and lines are read until a complete statement is formed or a syntax error is found. So, one way to interrupt the reading of an incomplete statement is to force a syntax error: adding a <B>`;' </B> in the middle of a statement is a sure way of forcing a syntax error (except inside multiline strings and comments; these must be closed explicitly). If a line starts with <B>`='</B>, then <B>lua</B> displays the values of all the expressions in the remainder of the line. The expressions must be separated by commas. The primary prompt is the value of the global variable <B>_PROMPT</B>, if this value is a string; otherwise, the default prompt is used. Similarly, the secondary prompt is the value of the global variable <B>_PROMPT2</B>. So, to change the prompts, set the corresponding variable to a string of your choice. You can do that after calling the interpreter or on the command line with <B>"_PROMPT" "=\'lua: \'"</B>, for example. (Note the need for quotes, because the string contains a space.) The default prompts are ``> '' and ``>> ''. <H1>OPTIONS</H1> <P> <B>-</B> load and execute the standard input as a file, that is, not interactively, even when the standard input is a terminal. <P> <B>-e "</B><I>stat"</I> execute statement <I>stat</I>. You need to quote <I>stat </I> if it contains spaces, quotes, or other characters special to the shell. <P> <B>-i</B> enter interactive mode after <I>script</I> is executed. <P> <B>-l "</B><I>file"</I> call <B>require( file</B><I>)</I> before executing <I></I>script. Typically used to load libraries (hence the letter <I>l</I>). <P> <B>-v</B> show version information. <H1>SEE ALSO</H1> <B>luac</B>(1) <BR> <A HREF="http://www.lua.org/">http://www.lua.org/</A> <H1>DIAGNOSTICS</H1> Error messages should be self explanatory. <H1>AUTHORS</H1> R. Ierusalimschy, L. H. de Figueiredo, and W. Celes (<A HREF="mailto:lua...@te...">lua AT tecgraf.puc-rio.br</A>) <!-- EOF --> </BODY> </HTML> --- NEW FILE: readme.html --- <HTML> <HEAD> <TITLE>Lua documentation</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <HR> <H1> <A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A> Documentation </H1> <UL> <LI><A HREF="http://www.lua.org/">Official web site</A> <LI><A HREF="contents.html">Reference manual</A> <LI><A HREF="lua.html">lua man page</A> <LI><A HREF="luac.html">luac man page</A> <LI><A HREF="../README">lua/README</A> <LI><A HREF="../src/README">lua/src/README</A> <LI><A HREF="../src/lib/README">lua/src/lib/README</A> <LI><A HREF="../src/lua/README">lua/src/lua/README</A> <LI><A HREF="../src/luac/README">lua/src/luac/README</A> <LI><A HREF="../etc/README">lua/etc/README</A> <LI><A HREF="../test/README">lua/test/README</A> </UL> <HR> <SMALL> Last update: Thu Mar 11 23:08:56 BRT 2004 </SMALL> </BODY> </HTML> --- NEW FILE: lua.1 --- .\" lua.man,v 1.8 2003/04/02 00:05:20 lhf Exp .TH LUA 1 "2003/04/02 00:05:20" .SH NAME lua \- Lua interpreter .SH SYNOPSIS .B lua [ .I options ] [ .I script [ .I args ] ] .SH DESCRIPTION .B lua is the stand-alone Lua interpreter. It loads and executes Lua programs, either in textual source form or in precompiled binary form. (Precompiled binaries are output by .BR luac , the Lua compiler.) .B lua can be used as a batch interpreter and also interactively. .LP The given .I options (see below) are executed and then the Lua program in file .I script is loaded and executed. The given .I args are available to .I script as strings in a global table named .BR arg . If these arguments contain spaces or other characters special to the shell, then they should be quoted (but note that the quotes will be removed by the shell). The arguments in .B arg start at 0, which contains the string .RI ` script '. The index of the last argument is stored in .BR "arg.n" . The arguments given in the command line before .IR script , including the name of the interpreter, are available in negative indices in .BR arg . .LP At the very start, before even handling the command line, .B lua executes the contents of the environment variable .BR LUA_INIT , if it is defined. If the value of .B LUA_INIT is of the form .RI `@ filename ', then .I filename is executed. Otherwise, the string is assumed to be a Lua statement and is executed. .LP Options start with .B \- and are described below. You can use .B "\--" to signal the end of options. .LP If no arguments are given, then .B "\-v \-i" is assumed when the standard input is a terminal; otherwise, .B "\-" is assumed. .LP In interactive mode, .B lua prompts the user, reads lines from the standard input, and executes them as they are read. If a line does not contain a complete statement, then a secondary prompt is displayed and lines are read until a complete statement is formed or a syntax error is found. So, one way to interrupt the reading of an incomplete statement is to force a syntax error: adding a .B `;' in the middle of a statement is a sure way of forcing a syntax error (except inside multiline strings and comments; these must be closed explicitly). If a line starts with .BR `=' , then .B lua displays the values of all the expressions in the remainder of the line. The expressions must be separated by commas. The primary prompt is the value of the global variable .BR _PROMPT , if this value is a string; otherwise, the default prompt is used. Similarly, the secondary prompt is the value of the global variable .BR _PROMPT2 . So, to change the prompts, set the corresponding variable to a string of your choice. You can do that after calling the interpreter or on the command line with .BR "_PROMPT" "=\'lua: \'" , for example. (Note the need for quotes, because the string contains a space.) The default prompts are ``> '' and ``>> ''. .SH OPTIONS .TP .B \- load and execute the standard input as a file, that is, not interactively, even when the standard input is a terminal. .TP .BI \-e " stat" execute statement .IR stat . You need to quote .I stat if it contains spaces, quotes, or other characters special to the shell. .TP .B \-i enter interactive mode after .I script is executed. .TP .BI \-l " file" call .BI require( file ) before executing .IR script. Typically used to load libraries (hence the letter .IR l ). .TP .B \-v show version information. .SH "SEE ALSO" .BR luac (1) .br http://www.lua.org/ .SH DIAGNOSTICS Error messages should be self explanatory. .SH AUTHORS R. Ierusalimschy, L. H. de Figueiredo, and W. Celes (lu...@te...) .\" EOF --- NEW FILE: logo.gif --- (This appears to be a binary file; contents omitted.) --- NEW FILE: manual.html --- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <TITLE>Lua: 5.0 reference manual</TITLE> </head> <body BGCOLOR="#FFFFFF"> <hr> <h1> <A HREF="http://www.lua.org/home.html"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A> Lua 5.0 Reference Manual </h1> by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes <p> <small> <a HREF="http://www.lua.org/copyright.html">Copyright</a> [...4573 lines suppressed...] fieldsep ::= `<b>,</b>´ | `<b>;</b>´ <p> binop ::= `<b>+</b>´ | `<b>-</b>´ | `<b>*</b>´ | `<b>/</b>´ | `<b>^</b>´ | `<b>..</b>´ | `<b><</b>´ | `<b><=</b>´ | `<b>></b>´ | `<b>>=</b>´ | `<b>==</b>´ | `<b>~=</b>´ | <b>and</b> | <b>or</b> <p> unop ::= `<b>-</b>´ | <b>not</b> <p></pre> <p> <p> <HR> <SMALL> Last update: Tue Nov 25 16:08:37 BRST 2003 </SMALL> </BODY> </HTML> |
From: John L. <jr...@us...> - 2005-06-06 23:06:24
|
Update of /cvsroot/wxlua/wxLua/modules/lua In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua Added Files: COPYRIGHT DIFFS HISTORY INSTALL MANIFEST Makefile README UPDATE config configure lslua50.def lslua50m.def lua50_wx26.dsp Log Message: moved files to the modules directory structure --- NEW FILE: DIFFS --- diff -r lua-5.0/COPYRIGHT lua-5.0.2/COPYRIGHT 12c12 < Copyright (C) 2003 Tecgraf, PUC-Rio. --- > Copyright (C) 2003-2004 Tecgraf, PUC-Rio. diff -r lua-5.0/Makefile lua-5.0.2/Makefile 98a99,101 > newer: > @find . -newer MANIFEST -type f > diff -r lua-5.0/doc/readme.html lua-5.0.2/doc/readme.html 16c16 < <LI><A HREF="manual.html">Reference manual</A> --- > <LI><A HREF="contents.html">Reference manual</A> 31c31 < Tue Apr 1 14:35:18 EST 2003 --- > Thu Mar 11 23:08:56 BRT 2004 diff -r lua-5.0/include/lua.h lua-5.0.2/include/lua.h 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 17,18c17,18 < #define LUA_VERSION "Lua 5.0" < #define LUA_COPYRIGHT "Copyright (C) 1994-2003 Tecgraf, PUC-Rio" --- > #define LUA_VERSION "Lua 5.0.2" > #define LUA_COPYRIGHT "Copyright (C) 1994-2004 Tecgraf, PUC-Rio" 368c368 < * Copyright (C) 1994-2003 Tecgraf, PUC-Rio. All rights reserved. --- > * Copyright (C) 1994-2004 Tecgraf, PUC-Rio. All rights reserved. diff -r lua-5.0/src/ldo.c lua-5.0.2/src/ldo.c 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 325,326c325 < if (nargs >= L->top - L->base) < luaG_runerror(L, "cannot resume dead coroutine"); --- > lua_assert(nargs < L->top - L->base); 329c328,329 < else if (ci->state & CI_YIELD) { /* inside a yield? */ --- > else { /* inside a yield */ > lua_assert(ci->state & CI_YIELD); 344,345d343 < else < luaG_runerror(L, "cannot resume non-suspended coroutine"); 351a350,358 > static int resume_error (lua_State *L, const char *msg) { > L->top = L->ci->base; > setsvalue2s(L->top, luaS_new(L, msg)); > incr_top(L); > lua_unlock(L); > return LUA_ERRRUN; > } > > 355a363,368 > if (L->ci == L->base_ci) { > if (nargs >= L->top - L->base) > return resume_error(L, "cannot resume dead coroutine"); > } > else if (!(L->ci->state & CI_YIELD)) /* not inside a yield? */ > return resume_error(L, "cannot resume non-suspended coroutine"); diff -r lua-5.0/src/lgc.c lua-5.0.2/src/lgc.c 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 113c113,114 < void luaC_separateudata (lua_State *L) { --- > size_t luaC_separateudata (lua_State *L) { > size_t deadmem = 0; 127a129 > deadmem += sizeudata(gcotou(curr)->uv.len); 136a139 > return deadmem; 247c250 < if (!(ci->state & CI_C) && lim < ci->top) --- > if (lim < ci->top) 390c393 < static void checkSizes (lua_State *L) { --- > static void checkSizes (lua_State *L, size_t deadmem) { 400c403 < G(L)->GCthreshold = 2*G(L)->nblocks; /* new threshold */ --- > G(L)->GCthreshold = 2*G(L)->nblocks - deadmem; /* new threshold */ 454c457,458 < static void mark (lua_State *L) { --- > static size_t mark (lua_State *L) { > size_t deadmem; 467c471 < luaC_separateudata(L); /* separate userdata to be preserved */ --- > deadmem = luaC_separateudata(L); /* separate userdata to be preserved */ 475a480 > return deadmem; 480c485 < mark(L); --- > size_t deadmem = mark(L); 482c487 < checkSizes(L); --- > checkSizes(L, deadmem); diff -r lua-5.0/src/lgc.h lua-5.0.2/src/lgc.h 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 18c18 < void luaC_separateudata (lua_State *L); --- > size_t luaC_separateudata (lua_State *L); diff -r lua-5.0/src/lib/lbaselib.c lua-5.0.2/src/lib/lbaselib.c 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 276a277 > int n = lua_gettop(L); 280c281 < return lua_gettop(L) - 1; --- > return lua_gettop(L) - n; 327c328 < char buff[64]; --- > char buff[128]; diff -r lua-5.0/src/lib/liolib.c lua-5.0.2/src/lib/liolib.c 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 161c161 < if (lua_isnone(L, 1)) { --- > if (lua_isnone(L, 1) && lua_type(L, lua_upvalueindex(1)) == LUA_TTABLE) { 178c178 < char buff[32]; --- > char buff[128]; diff -r lua-5.0/src/lparser.c lua-5.0.2/src/lparser.c 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 1143a1144 > FuncState *fs = ls->fs; 1145c1146,1147 < init_exp(&v, VLOCAL, ls->fs->freereg++); --- > init_exp(&v, VLOCAL, fs->freereg); > luaK_reserveregs(fs, 1); 1148c1150,1152 < luaK_storevar(ls->fs, &v, &b); --- > luaK_storevar(fs, &v, &b); > /* debug information will only see the variable after this point! */ > getlocvar(fs, fs->nactvar - 1).startpc = fs->pc; diff -r lua-5.0/src/luac/Makefile lua-5.0.2/src/luac/Makefile 16c16 < $(CC) -o $@ $(MYLDFLAGS) $(OBJS) -L$(LIB) -llua -llualib $(EXTRA_LIBS) --- > $(CC) -o $@ $(MYLDFLAGS) $(OBJS) -L$(LIB) -llua -llualib $(EXTRA_LIBS) $(DLLIB) diff -r lua-5.0/src/luac/luac.c lua-5.0.2/src/luac/luac.c 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 184a185 > lua_lock(L); 185a187 > lua_unlock(L); diff -r lua-5.0/src/lvm.c lua-5.0.2/src/lvm.c 2c2 < ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ --- > ** $Id: DIFFS,v 1.1 2005/06/06 23:06:14 jrl1 Exp $ 69c69 < if (mask > LUA_MASKLINE) { /* instruction-hook set? */ --- > if (mask & LUA_MASKCOUNT) { /* instruction-hook set? */ 402,403c402,403 < L->ci->u.l.pc = &pc; < if (L->hookmask & LUA_MASKCALL) --- > if (L->hookmask & LUA_MASKCALL) { > L->ci->u.l.pc = &pc; 404a405 > } 405a407 > L->ci->u.l.pc = &pc; 676,678c678 < lua_assert(ci->u.l.pc == &pc && < ttisfunction(ci->base - 1) && < (ci->state & CI_SAVEDPC)); --- > lua_assert(ttisfunction(ci->base - 1) && (ci->state & CI_SAVEDPC)); 779a780 > diff -r lua-5.0/test/luac.lua lua-5.0.2/test/luac.lua 4,6c4,6 < assert(arg[1]~=nil,"usage: lua luac.lua file.lua") < f=assert(io.open("luac.out","w")) < f:write(string.dump(loadfile(arg[1]))) --- > assert(arg[1]~=nil and arg[2]==nil,"usage: lua luac.lua file.lua") > f=assert(io.open("luac.out","wb")) > f:write(string.dump(assert(loadfile(arg[1])))) diff -r lua-5.0/test/table.lua lua-5.0.2/test/table.lua 8c8 < local _,_,a,b=string.find(l,'"?(%w+)"?%s*(.*)$') --- > local _,_,a,b=string.find(l,'"?([_%w]+)"?%s*(.*)$') --- NEW FILE: lua50_wx26.dsp --- # Microsoft Developer Studio Project File - Name="lua50_wx26" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Static Library" 0x0104 CFG=lua50_wx26 - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "lua50_wx26.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "lua50_wx26.mak" CFG="lua50_wx26 - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "lua50_wx26 - Win32 Release" (based on "Win32 (x86) Static Library") !MESSAGE "lua50_wx26 - Win32 Debug" (based on "Win32 (x86) Static Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "lua50_wx26 - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "vc_msw_wx26" # PROP BASE Intermediate_Dir "vc_msw_wx26" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "vc_msw_wx26" # PROP Intermediate_Dir "vc_msw_wx26" # PROP Target_Dir "" # ADD BASE CPP /nologo /FD /GR /GX /MD /O1 /GR /GX /I "include" /I "." /W4 /D "WIN32" /D "_LIB" /D "WXLUA_CODE" /c # ADD CPP /nologo /FD /GR /GX /MD /O1 /GR /GX /I "include" /I "." /W4 /D "WIN32" /D "_LIB" /D "WXLUA_CODE" /c # ADD BASE RSC /l 0x405 # ADD RSC /l 0x405 BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LIB32=link.exe -lib # ADD BASE LIB32 /nologo /out:"..\lib\lua50_wx26.lib" # ADD LIB32 /nologo /out:"..\lib\lua50_wx26.lib" !ELSEIF "$(CFG)" == "lua50_wx26 - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "vc_mswd_wx26" # PROP BASE Intermediate_Dir "vc_mswd_wx26" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "vc_mswd_wx26" # PROP Intermediate_Dir "vc_mswd_wx26" # PROP Target_Dir "" # ADD BASE CPP /nologo /FD /GR /GX /MDd /Od /GR /GX /I "include" /I "." /W4 /Zi /Gm /GZ /D "WIN32" /D "_LIB" /D "_DEBUG" /D "WXLUA_CODE" /c # ADD CPP /nologo /FD /GR /GX /MDd /Od /GR /GX /I "include" /I "." /W4 /Zi /Gm /GZ /D "WIN32" /D "_LIB" /D "_DEBUG" /D "WXLUA_CODE" /c # ADD BASE RSC /l 0x405 # ADD RSC /l 0x405 BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LIB32=link.exe -lib # ADD BASE LIB32 /nologo /out:"..\lib\lua50d_wx26.lib" # ADD LIB32 /nologo /out:"..\lib\lua50d_wx26.lib" !ENDIF # Begin Target # Name "lua50_wx26 - Win32 Release" # Name "lua50_wx26 - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=.\SRC\LAPI.C # End Source File # Begin Source File SOURCE=.\SRC\LAPI.H # End Source File # Begin Source File SOURCE=.\SRC\LIB\LAUXLIB.C # End Source File # Begin Source File SOURCE=.\SRC\LIB\LBASELIB.C # End Source File # Begin Source File SOURCE=.\SRC\LCODE.C # End Source File # Begin Source File SOURCE=.\SRC\LCODE.H # End Source File # Begin Source File SOURCE=.\SRC\LIB\LDBLIB.C # End Source File # Begin Source File SOURCE=.\SRC\LDEBUG.C # End Source File # Begin Source File SOURCE=.\SRC\LDEBUG.H # End Source File # Begin Source File SOURCE=.\SRC\LDLLMAIN.C # End Source File # Begin Source File SOURCE=.\SRC\LDO.C # End Source File # Begin Source File SOURCE=.\SRC\LDO.H # End Source File # Begin Source File SOURCE=.\src\ldump.c # End Source File # Begin Source File SOURCE=.\SRC\LFUNC.C # End Source File # Begin Source File SOURCE=.\SRC\LFUNC.H # End Source File # Begin Source File SOURCE=.\SRC\LGC.C # End Source File # Begin Source File SOURCE=.\SRC\LGC.H # End Source File # Begin Source File SOURCE=.\SRC\LIB\LIOLIB.C # End Source File # Begin Source File SOURCE=.\SRC\LLEX.C # End Source File # Begin Source File SOURCE=.\SRC\LLEX.H # End Source File # Begin Source File SOURCE=.\SRC\LLIMITS.H # End Source File # Begin Source File SOURCE=.\SRC\LIB\LMATHLIB.C # End Source File # Begin Source File SOURCE=.\SRC\LMEM.C # End Source File # Begin Source File SOURCE=.\SRC\LMEM.H # End Source File # Begin Source File SOURCE=.\src\lib\loadlib.c # End Source File # Begin Source File SOURCE=.\SRC\LOBJECT.C # End Source File # Begin Source File SOURCE=.\SRC\LOBJECT.H # End Source File # Begin Source File SOURCE=.\SRC\LOPCODES.C # End Source File # Begin Source File SOURCE=.\SRC\LOPCODES.H # End Source File # Begin Source File SOURCE=.\SRC\LPARSER.C # End Source File # Begin Source File SOURCE=.\SRC\LPARSER.H # End Source File # Begin Source File SOURCE=.\lslua50m.def # End Source File # Begin Source File SOURCE=.\SRC\LSTATE.C # End Source File # Begin Source File SOURCE=.\SRC\LSTATE.H # End Source File # Begin Source File SOURCE=.\SRC\LSTRING.C # End Source File # Begin Source File SOURCE=.\SRC\LSTRING.H # End Source File # Begin Source File SOURCE=.\SRC\LIB\LSTRLIB.C # End Source File # Begin Source File SOURCE=.\SRC\LTABLE.C # End Source File # Begin Source File SOURCE=.\SRC\LTABLE.H # End Source File # Begin Source File SOURCE=.\src\lib\ltablib.c # End Source File # Begin Source File SOURCE=.\SRC\LTESTS.C # End Source File # Begin Source File SOURCE=.\SRC\LTM.C # End Source File # Begin Source File SOURCE=.\SRC\LTM.H # End Source File # Begin Source File SOURCE=.\SRC\LUNDUMP.C # End Source File # Begin Source File SOURCE=.\SRC\LUNDUMP.H # End Source File # Begin Source File SOURCE=.\SRC\LVM.C # End Source File # Begin Source File SOURCE=.\SRC\LVM.H # End Source File # Begin Source File SOURCE=.\SRC\LZIO.C # End Source File # Begin Source File SOURCE=.\SRC\LZIO.H # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=.\INCLUDE\LAUXLIB.H # End Source File # Begin Source File SOURCE=.\INCLUDE\LUA.H # End Source File # Begin Source File SOURCE=.\INCLUDE\LUADEBUG.H # End Source File # Begin Source File SOURCE=.\INCLUDE\LUALIB.H # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project --- NEW FILE: configure --- #!/bin/sh # Lua does not use GNU autoconf; just edit ./config if needed to suit your # platform and then run make. # This shows the parameters currently set in ./config: make echo # If you want config as a Lua program, run "make lecho". --- NEW FILE: COPYRIGHT --- Lua License ----------- Lua is licensed under the terms of the MIT license reproduced below. This means that Lua is free software and can be used for both academic and commercial purposes at absolutely no cost. For details and rationale, see http://www.lua.org/license.html . =============================================================================== Copyright (C) 2003-2004 Tecgraf, PUC-Rio. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== (end of COPYRIGHT) --- NEW FILE: lslua50.def --- EXPORTS _lua_open _lua_close _lua_newthread _lua_atpanic _lua_gettop _lua_settop _lua_pushvalue _lua_remove _lua_insert _lua_replace _lua_checkstack _lua_xmove _lua_isnumber _lua_isstring _lua_iscfunction _lua_isuserdata _lua_type _lua_typename _lua_equal _lua_rawequal _lua_lessthan _lua_tonumber _lua_toboolean _lua_tostring _lua_strlen _lua_tocfunction _lua_touserdata _lua_tothread _lua_topointer _lua_pushnil _lua_pushnumber _lua_pushlstring _lua_pushstring _lua_pushvfstring _lua_pushfstring ; varargs _lua_pushcclosure _lua_pushboolean _lua_pushlightuserdata _lua_gettable _lua_rawget _lua_rawgeti _lua_newtable _lua_newuserdata _lua_getmetatable _lua_getfenv _lua_settable _lua_rawset _lua_rawseti _lua_setmetatable _lua_setfenv _lua_call _lua_pcall _lua_cpcall _lua_load _lua_dump _lua_yield _lua_resume _lua_getgcthreshold _lua_getgccount _lua_setgcthreshold _lua_version _lua_error _lua_next _lua_concat _lua_pushupvalues _lua_getstack _lua_getinfo _lua_getlocal _lua_setlocal _lua_getupvalue _lua_setupvalue _lua_sethook _lua_gethook _lua_gethookmask _lua_gethookcount _lua_dofile _lua_dostring _lua_dobuffer _luaL_openlib _luaL_getmetafield _luaL_callmeta _luaL_typerror _luaL_argerror _luaL_checklstring _luaL_optlstring _luaL_checknumber _luaL_optnumber _luaL_checkstack _luaL_checktype _luaL_checkany _luaL_newmetatable _luaL_getmetatable _luaL_checkudata _luaL_where _luaL_error ; varargs _luaL_findstring _luaL_ref _luaL_unref _luaL_getn _luaL_setn _luaL_loadfile _luaL_loadbuffer _luaL_buffinit _luaL_prepbuffer _luaL_addlstring _luaL_addstring _luaL_addvalue _luaL_pushresult _lua_dofile _lua_dostring _lua_dobuffer _luaopen_base _luaopen_table _luaopen_io _luaopen_string _luaopen_math _luaopen_debug _luaopen_loadlib --- NEW FILE: Makefile --- # makefile for Lua hierarchy # see INSTALL for installation instructions # see config for customization instructions LUA= . include $(LUA)/config # primary targets ("co" and "klean" are used for making the distribution) all clean co klean: dirs cd include; $(MAKE) $@ cd src; $(MAKE) $@ cd src/lib; $(MAKE) $@ cd src/luac; $(MAKE) $@ cd src/lua; $(MAKE) $@ cd wxluautil; $(MAKE) $@ # in case they were not created during unpacking dirs: bin lib bin lib: mkdir -p $@ # simple test to see Lua working test: all bin/lua test/hello.lua # remove debug information from binaries strip: $(STRIP) bin/* # official installation install: all strip mkdir -p $(INSTALL_BIN) $(INSTALL_INC) $(INSTALL_LIB) $(INSTALL_MAN) $(INSTALL_EXEC) bin/* $(INSTALL_BIN) $(INSTALL_DATA) include/*.h $(INSTALL_INC) $(INSTALL_DATA) lib/*.a $(INSTALL_LIB) $(INSTALL_DATA) doc/*.1 $(INSTALL_MAN) # shared libraries (for Linux) so: ld -o lib/liblua.so.$V -shared src/*.o ld -o lib/liblualib.so.$V -shared src/lib/*.o cd lib; ln -fs liblua.so.$V liblua.so; ln -fs liblualib.so.$V liblualib.so # binaries using shared libraries sobin: rm -f bin/* cd src/lua; $(MAKE) cd src/luac; $(MAKE) # install shared libraries soinstall: $(INSTALL_EXEC) lib/*.so.* $(INSTALL_LIB) cd $(INSTALL_LIB); ln -fs liblua.so.$V liblua.so; ln -fs liblualib.so.$V liblualib.so # clean shared libraries soclean: rm -f lib/*.so* bin/* # echo config parameters echo: @echo "" @echo "These are the parameters currently set in $(LUA)/config to build Lua $V:" @echo "" @echo "LOADLIB = $(LOADLIB)" @echo "DLLIB = $(DLLIB)" @echo "NUMBER = $(NUMBER)" @echo "POPEN = $(POPEN)" @echo "TMPNAM = $(TMPNAM)" @echo "DEGREES = $(DEGREES)" @echo "USERCONF = $(USERCONF)" @echo "CC = $(CC)" @echo "WARN = $(WARN)" @echo "MYCFLAGS = $(MYCFLAGS)" @echo "MYLDFLAGS = $(MYLDFLAGS)" @echo "EXTRA_LIBS = $(EXTRA_LIBS)" @echo "AR = $(AR)" @echo "RANLIB = $(RANLIB)" @echo "STRIP = $(STRIP)" @echo "INSTALL_ROOT = $(INSTALL_ROOT)" @echo "INSTALL_BIN = $(INSTALL_BIN)" @echo "INSTALL_INC = $(INSTALL_INC)" @echo "INSTALL_LIB = $(INSTALL_LIB)" @echo "INSTALL_MAN = $(INSTALL_MAN)" @echo "INSTALL_EXEC = $(INSTALL_EXEC)" @echo "INSTALL_DATA = $(INSTALL_DATA)" @echo "" @echo "Edit $(LUA)/config if needed to suit your platform and then run make." @echo "" # turn config into Lua code # uncomment the last sed expression if you want nil instead of empty strings lecho: @echo "-- $(LUA)/config for Lua $V" @echo "VERSION = '$(V)'" @make echo | grep = | sed -e 's/= /= "/' -e 's/$$/"/' #-e 's/""/nil/' @echo "-- EOF" newer: @find . -newer MANIFEST -type f # (end of Makefile) --- NEW FILE: UPDATE --- This is Lua 5.0.2, an update of Lua 5.0 that includes the following changes, which fix all known bugs in Lua 5.0. For the exact differences, see DIFFS. src/ldo.c Attempt to resume running coroutine crashed Lua src/lgc.c C functions also may have stacks larger than current top Userdata to be collected still counted into new GC threshold src/lgc.h Userdata to be collected still counted into new GC threshold src/lparser.c Syntax `local function' did not increment stack size src/lvm.c `pc' address was invalidated when a coroutine was suspended Count hook might be called without being set src/lib/lbaselib.c Buffer overflow for unusual %p representation Wrong number of returns from chunks loaded from stdin src/lib/liolib.c `file.close()' could not be called without arguments Buffer overflow for unusual %p representation src/luac/luac.c Missing lock/unlock --- NEW FILE: MANIFEST --- MANIFEST contents of Lua 5.0.2 distribution on Wed Mar 17 17:59:01 BRT 2004 lua-5.0.2 lua-5.0.2/COPYRIGHT lua-5.0.2/DIFFS lua-5.0.2/HISTORY lua-5.0.2/INSTALL lua-5.0.2/MANIFEST lua-5.0.2/Makefile lua-5.0.2/README lua-5.0.2/UPDATE lua-5.0.2/bin lua-5.0.2/build lua-5.0.2/config lua-5.0.2/configure lua-5.0.2/doc lua-5.0.2/doc/contents.html lua-5.0.2/doc/logo.gif lua-5.0.2/doc/lua.1 lua-5.0.2/doc/lua.html lua-5.0.2/doc/luac.1 lua-5.0.2/doc/luac.html lua-5.0.2/doc/manual.html lua-5.0.2/doc/readme.html lua-5.0.2/etc lua-5.0.2/etc/Makefile lua-5.0.2/etc/README lua-5.0.2/etc/bin2c.c lua-5.0.2/etc/compat.lua lua-5.0.2/etc/doall.lua lua-5.0.2/etc/lua.ico lua-5.0.2/etc/lua.magic lua-5.0.2/etc/lua.xpm lua-5.0.2/etc/luser_number.h lua-5.0.2/etc/luser_tests.h lua-5.0.2/etc/min.c lua-5.0.2/etc/noparser.c lua-5.0.2/etc/saconfig.c lua-5.0.2/etc/trace.c lua-5.0.2/include lua-5.0.2/include/Makefile lua-5.0.2/include/lauxlib.h lua-5.0.2/include/lua.h lua-5.0.2/include/lualib.h lua-5.0.2/lib lua-5.0.2/src lua-5.0.2/src/Makefile lua-5.0.2/src/README lua-5.0.2/src/lapi.c lua-5.0.2/src/lapi.h lua-5.0.2/src/lcode.c lua-5.0.2/src/lcode.h lua-5.0.2/src/ldebug.c lua-5.0.2/src/ldebug.h lua-5.0.2/src/ldo.c lua-5.0.2/src/ldo.h lua-5.0.2/src/ldump.c lua-5.0.2/src/lfunc.c lua-5.0.2/src/lfunc.h lua-5.0.2/src/lgc.c lua-5.0.2/src/lgc.h lua-5.0.2/src/lib lua-5.0.2/src/lib/Makefile lua-5.0.2/src/lib/README lua-5.0.2/src/lib/lauxlib.c lua-5.0.2/src/lib/lbaselib.c lua-5.0.2/src/lib/ldblib.c lua-5.0.2/src/lib/liolib.c lua-5.0.2/src/lib/lmathlib.c lua-5.0.2/src/lib/loadlib.c lua-5.0.2/src/lib/lstrlib.c lua-5.0.2/src/lib/ltablib.c lua-5.0.2/src/llex.c lua-5.0.2/src/llex.h lua-5.0.2/src/llimits.h lua-5.0.2/src/lmem.c lua-5.0.2/src/lmem.h lua-5.0.2/src/lobject.c lua-5.0.2/src/lobject.h lua-5.0.2/src/lopcodes.c lua-5.0.2/src/lopcodes.h lua-5.0.2/src/lparser.c lua-5.0.2/src/lparser.h lua-5.0.2/src/lstate.c lua-5.0.2/src/lstate.h lua-5.0.2/src/lstring.c lua-5.0.2/src/lstring.h lua-5.0.2/src/ltable.c lua-5.0.2/src/ltable.h lua-5.0.2/src/ltests.c lua-5.0.2/src/ltm.c lua-5.0.2/src/ltm.h lua-5.0.2/src/lua lua-5.0.2/src/lua/Makefile lua-5.0.2/src/lua/README lua-5.0.2/src/lua/lua.c lua-5.0.2/src/luac lua-5.0.2/src/luac/Makefile lua-5.0.2/src/luac/README lua-5.0.2/src/luac/luac.c lua-5.0.2/src/luac/print.c lua-5.0.2/src/lundump.c lua-5.0.2/src/lundump.h lua-5.0.2/src/lvm.c lua-5.0.2/src/lvm.h lua-5.0.2/src/lzio.c lua-5.0.2/src/lzio.h lua-5.0.2/test lua-5.0.2/test/README lua-5.0.2/test/bisect.lua lua-5.0.2/test/cf.lua lua-5.0.2/test/echo.lua lua-5.0.2/test/env.lua lua-5.0.2/test/factorial.lua lua-5.0.2/test/fib.lua lua-5.0.2/test/fibfor.lua lua-5.0.2/test/globals.lua lua-5.0.2/test/hello.lua lua-5.0.2/test/life.lua lua-5.0.2/test/lua lua-5.0.2/test/luac lua-5.0.2/test/luac.lua lua-5.0.2/test/printf.lua lua-5.0.2/test/readonly.lua lua-5.0.2/test/sieve.lua lua-5.0.2/test/sort.lua lua-5.0.2/test/table.lua lua-5.0.2/test/trace-calls.lua lua-5.0.2/test/trace-globals.lua lua-5.0.2/test/undefined.lua lua-5.0.2/test/xd.lua END OF MANIFEST --- NEW FILE: INSTALL --- This is Lua 5.0. * Installation ------------ Building Lua on a Unix system should be very easy: 1. Read "config" and edit it to suit your platform and needs. We strongly recommend that you enable support for dynamic loading, if your platform allows it. 2. Do "make". 3. If you want to install Lua in an "official" place in your system, then do "make install". The official place and the way to install files are defined in "config". You may have to be root to do this. See below for instructions for Windows and other systems. * What you get ------------ If "make" succeeds, you get: * an interpreter in ./bin/lua and a compiler in ./bin/luac; * libraries in ./lib; * include files in ./include. These are the only directories you need for development. There are man pages for lua and luac, in both nroff and html; a reference manual in html in ./doc, some sample code in ./test, and some useful stuff in ./etc. You don't need these directories for development. See also the README files in the various subdirectories. A convenient starting point is ./doc/readme.html. * If you have problems (and solutions!) ------------------------------------- If "make" fails, please let us know (lu...@te...). If you make changes to "config" or to the Makefiles, please send them to us. * Shared libraries ---------------- If you are running Linux, do "make so" after "make" succeeds. This will create shared libraries in ./lib. To install those shared libraries in an official place, do "make soinstall". If you want the interpreter and the compiler to use shared libraries, then do "make sobin" too. You may want to do this before "make install". If you only want the shared libraries, you may want to add -fPIC to MYCFLAGS in "config". Also, you may need to run "ldconfig" as root. You may need to include ./lib in the LD_LIBRARY_PATH environment variable to link programs that use the shared libraries if you don't put them in the official places with "make install". (You may need to use the full path.) Building shared libraries in other systems is similar but details differ; you may need to fix a few details in the top-level Makefile. * Installation on Windows and other systems ----------------------------------------------------- The instructions for building Lua on other systems machine depend on the particular compiler you are using. The simplest way is to create a folder with all .c and .h files, and then create projects for the core library, the standard library, the interpreter, and the compiler, as follows: core lib: lapi.c lcode.c ldebug.c ldo.c ldump.c lfunc.c lgc.c llex.c lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c ltable.c ltests.c ltm.c lundump.c lvm.c lzio.c standard lib: lauxlib.c lbaselib.c ldblib.c liolib.c lmathlib.c ltablib.c lstrlib.c loadlib.c interpreter: core lib, standard lib, lua.c compiler: core lib, standard lib, luac.c print.c and also lopcodes.c (with LUA_OPNAMES defined) from core. Of course, to use Lua as a library, you'll have to know how to create and use libraries with your compiler. Also, read "config" to see what can be customized at compilation time. (end of INSTALL) --- NEW FILE: README --- This is Lua 5.0. See HISTORY for a summary of changes since the last released version. * What is Lua? ------------ Lua is a powerful, light-weight programming language designed for extending applications. Lua is also frequently used as a general-purpose, stand-alone language. Lua is free software. For complete information, visit Lua's web site at http://www.lua.org/ . For an executive summary, see http://www.lua.org/about.html . Lua has been used in many different projects around the world. For a short list, see http://www.lua.org/uses.html . * Availability ------------ Lua is freely available for both academic and commercial purposes. See COPYRIGHT and http://www.lua.org/license.html for details. Lua can be downloaded from its official site http://www.lua.org/ and several other sites aroung the world. For a complete list of mirror sites, see http://www.lua.org/mirrors.html . * Installation ------------ Lua is implemented in pure ANSI C, and compiles unmodified in all known platforms that have an ANSI C compiler. Under Unix, simply typing "make" should work. See INSTALL for detailed instructions. * Contacting the authors ---------------------- Send your comments, questions, and bug reports to lu...@te.... For more information about the authors, see http://www.lua.org/authors.html . For reporting bugs, try also the mailing list: lu...@te.... For more information about this list, including instructions on how to subscribe and access the archives, see http://www.lua.org/lua-l.html . * Origin ------ Lua is developed at Tecgraf, the Computer Graphics Technology Group of PUC-Rio (the Pontifical Catholic University of Rio de Janeiro in Brazil). Tecgraf is a laboratory of the Department of Computer Science. (end of README) --- NEW FILE: config --- # configuration file for making Lua 5.0 # see INSTALL for installation instructions # These are default values. Skip this section and see the explanations below. LOADLIB= DLLIB= NUMBER= POPEN= TMPNAM= DEGREES= USERCONF= # == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================= # --------------------------------------------------------------- Lua libraries # Support for dynamically loading C libraries for Lua is a very important # feature, which we strongly recommend be enabled. By default, this support is # enabled on Windows systems (see below) but disabled on other systems because # it relies on system-dependent code that is not part of ANSI C. For more # information on dynamic loading, read the comments in src/lib/liolib.c . # # To enable support for dynamic loading on Unix systems that support the dlfcn # interface (e.g., Linux, Solaris, IRIX, BSD, AIX, HPUX, and probably others), # uncomment the next two lines. # #LOADLIB= -DUSE_DLOPEN=1 #DLLIB= -ldl # # In Linux with gcc, you should also uncomment the next definition for # MYLDFLAGS, which passes -E (= -export-dynamic) to the linker. This option # allows dynamic libraries to link back to the `lua' program, so that they do # not need the Lua libraries. (Other systems may have an equivalent facility.) # #MYLDFLAGS= -Wl,-E # # On Windows systems. support for dynamic loading is enabled by default. # To disable this support, uncomment the next line. # #LOADLIB= -DUSE_DLL=0 # The Lua IO library (src/lib/liolib.c) has support for pipes using popen and # pclose. This support is enabled by default on POSIX systems. # If your system is not POSIX but has popen and pclose, define USE_POPEN=1. # If you don't want to support pipes, define USE_POPEN=0. # #POPEN= -DUSE_POPEN=1 #POPEN= -DUSE_POPEN=0 # # The form below will probably work in (some) Windows systems. # #POPEN= -DUSE_POPEN=1 -Dpopen=_popen -Dpclose=_pclose # The Lua OS library (src/lib/liolib.c) exports an interface to the C function # tmpnam, which gcc now thinks is `dangerous'. So, support for tmpnam is # disabled by default when compiling with gcc. # If you still want to use tmpnam, define USE_TMPNAME=1. If you don't want to # use tmpnam even if you're not compiling with gcc, define USE_TMPNAME=0. # #TMPNAM= -DUSE_TMPNAME=1 #TMPNAM= -DUSE_TMPNAME=0 # The Lua math library (src/lib/lmathlib.c) now operates in radians, unlike # previous versions of Lua, which used degrees. To use degrees instead of # radians, define USE_DEGREES. # #DEGREES= -DUSE_DEGREES # ------------------------------------------------------------------ Lua core # Lua uses double for numbers. To change this, uncomment and edit the following # line, changing USE_XXX to one of USE_DOUBLE, USE_FLOAT, USE_LONG, USE_INT. # #NUMBER= -DLUA_USER_H='"../etc/luser_number.h"' -DUSE_XXX # When compiling Lua with gcc on a Pentium machine, using a fast rounding # method for the conversion of doubles to ints can give around 20% speed # improvement. To use this rounding method, uncomment the following line. #NUMBER= -DLUA_USER_H='"../etc/luser_number.h"' -DUSE_FASTROUND # For partial compatibility with old upvalue syntax, define LUA_COMPATUPSYNTAX. # For partial compatibility with old upvalue behavior in C functions, define # LUA_COMPATUPVALUES. Add these definitions to MYCFLAGS. # # -DLUA_COMPATUPSYNTAX -DLUA_COMPATUPVALUES # ------------------------------------------------------------- Lua interpreter # The stand-alone Lua interpreter needs the math functions, which are usually # in libm.a (-lm). If your C library already includes the math functions, # or if you are using a modified interpreter that does not need them, # then comment the following line or add the appropriates libraries. # EXTRA_LIBS= -lm # If you want to customize the stand-alone Lua interpreter, uncomment and # edit the following two lines; also edit etc/saconfig.c to suit your needs. # -DUSE_READLINE adds line editing and history to the interpreter. You need # to add -lreadline (and perhaps also -lhistory and -lcurses or -lncurses) # to EXTRA_LIBS. # #USERCONF=-DLUA_USERCONFIG='"$(LUA)/etc/saconfig.c"' -DUSE_READLINE #EXTRA_LIBS= -lm -ldl -lreadline # -lhistory -lcurses -lncurses # ------------------------------------------------------------------ C compiler # You need an ANSI C compiler. gcc is a popular one. We do not use -ansi in # WARN because it disables POSIX features used in the libraries. # CC= gcc WARN= -Wall # ------------------------------------------------------------------ C options # Write here any options you may need for your C compiler. # If you are using gcc, -O3 will get you a faster but larger code. You can # also add -fomit-frame-pointer to get even faster code at the cost of losing # debug information. If you only want the shared libraries, you may want to # add -fPIC to MYCFLAGS. # MYCFLAGS= -O2 -DWXLUA_CODE #MYCFLAGS= -O3 -fomit-frame-pointer # -fPIC # Write here any options you may need for your C linker. #MYLDFLAGS= # ------------------------------------------------------------------ librarian # This should work in all Unix systems. # AR= ar rcu # If your system doesn't have (or need) ranlib, use RANLIB=true. # On some systems, "ar s" does what ranlib would do. # RANLIB= ranlib #RANLIB= ar s #RANLIB= true # ------------------------------------------------------------------ stripper # This should work in all Unix systems, but you may want to add options. # STRIP= strip # ------------------------------------------------------------------ install # Locations for "make install". You may need to be root do "make install". # INSTALL_ROOT= /usr/local INSTALL_BIN= $(INSTALL_ROOT)/bin INSTALL_INC= $(INSTALL_ROOT)/include INSTALL_LIB= $(INSTALL_ROOT)/lib INSTALL_MAN= $(INSTALL_ROOT)/man/man1 # You may prefer to use "install" instead of "cp" if you have it. # If you use "install", you may also want to change the permissions after -m. # INSTALL_EXEC= cp INSTALL_DATA= cp #INSTALL_EXEC= install -m 0755 #INSTALL_DATA= install -m 0644 # == END OF USER SETTINGS. NO NEED TO CHANGE ANYTHING BELOW THIS LINE ========= V=5.0 BIN= $(LUA)/bin INC= $(LUA)/include LIB= $(LUA)/lib INCS= -I$(INC) $(EXTRA_INCS) DEFS= $(NUMBER) $(EXTRA_DEFS) CFLAGS= $(MYCFLAGS) $(WARN) $(INCS) $(DEFS) # (end of config) --- NEW FILE: lslua50m.def --- EXPORTS lua_open lua_close lua_newthread lua_atpanic lua_gettop lua_settop lua_pushvalue lua_remove lua_insert lua_replace lua_checkstack lua_xmove lua_isnumber lua_isstring lua_iscfunction lua_isuserdata lua_type lua_typename lua_equal lua_rawequal lua_lessthan lua_tonumber lua_toboolean lua_tostring lua_strlen lua_tocfunction lua_touserdata lua_tothread lua_topointer lua_pushnil lua_pushnumber lua_pushlstring lua_pushstring lua_pushvfstring lua_pushfstring ; varargs lua_pushcclosure lua_pushboolean lua_pushlightuserdata lua_gettable lua_rawget lua_rawgeti lua_newtable lua_newuserdata lua_getmetatable lua_getfenv lua_settable lua_rawset lua_rawseti lua_setmetatable lua_setfenv lua_call lua_pcall lua_cpcall lua_load lua_dump lua_yield lua_resume lua_getgcthreshold lua_getgccount lua_setgcthreshold lua_version lua_error lua_next lua_concat lua_pushupvalues lua_getstack lua_getinfo lua_getlocal lua_setlocal lua_getupvalue lua_setupvalue lua_sethook lua_gethook lua_gethookmask lua_gethookcount lua_dofile lua_dostring lua_dobuffer luaL_openlib luaL_getmetafield luaL_callmeta luaL_typerror luaL_argerror luaL_checklstring luaL_optlstring luaL_checknumber luaL_optnumber luaL_checkstack luaL_checktype luaL_checkany luaL_newmetatable luaL_getmetatable luaL_checkudata luaL_where luaL_error ; varargs luaL_findstring luaL_ref luaL_unref luaL_getn luaL_setn luaL_loadfile luaL_loadbuffer luaL_buffinit luaL_prepbuffer luaL_addlstring luaL_addstring luaL_addvalue luaL_pushresult lua_dofile lua_dostring lua_dobuffer luaopen_base luaopen_table luaopen_io luaopen_string luaopen_math luaopen_debug luaopen_loadlib --- NEW FILE: HISTORY --- This is Lua 5.0. * Changes from version 4.0 to 5.0 ------------------------------- Language: + lexical scoping. + Lua coroutines. + standard libraries now packaged in tables. + tags replaced by metatables and tag methods replaced by metamethods, stored in metatables. + proper tail calls. + each function can have its own global table, which can be shared. + new __newindex metamethod, called when we insert a new key into a table. + new block comments: --[[ ... ]]. + new generic for. + new weak tables. + new boolean type. + new syntax "local function". + (f()) returns the first value returned by f. + {f()} fills a table with all values returned by f. + \n ignored in [[\n . + fixed and-or priorities. + more general syntax for function definition (e.g. function a.x.y:f()...end). + more general syntax for function calls (e.g. (print or write)(9)). + new functions (time/date, tmpfile, unpack, require, load*, etc.). API: + chunks are loaded by using lua_load; new luaL_loadfile and luaL_loadbuffer. + introduced lightweight userdata, a simple "void*" without a metatable. + new error handling protocol: the core no longer prints error messages; all errors are reported to the caller on the stack. + new lua_atpanic for host cleanup. + new, signal-safe, hook scheme. Implementation: + new license: MIT. + new, faster, register-based virtual machine. + support for external multithreading and coroutines. + new and consistent error message format. + the core no longer needs "stdio.h" for anything (except for a single use of sprintf to convert numbers to strings). + lua.c now runs the environment variable LUA_INIT, if present. It can be "@filename", to run a file, or the chunk itself. + support for user extensions in lua.c. sample implementation given for command line editing. + new dynamic loading library, active by default on several platforms. + safe garbage-collector metamethods. + precompiled bytecodes checked for integrity (secure binary dostring). + strings are fully aligned. + position capture in string.find. + read('*l') can read lines with embedded zeros. * Changes from version 3.2 to 4.0 ------------------------------- Language: + new "break" and "for" statements (both numerical and for tables). + uniform treatment of globals: globals are now stored in a Lua table. + improved error messages. + no more '$debug': full speed *and* full debug information. + new read form: read(N) for next N bytes. + general read patterns now deprecated. (still available with -DCOMPAT_READPATTERNS.) + all return values are passed as arguments for the last function (old semantics still available with -DLUA_COMPAT_ARGRET) + garbage collection tag methods for tables now deprecated. + there is now only one tag method for order. API: + New API: fully re-entrant, simpler, and more efficient. + New debug API. Implementation: + faster than ever: cleaner virtual machine and new hashing algorithm. + non-recursive garbage-collector algorithm. + reduced memory usage for programs with many strings. + improved treatment for memory allocation errors. + improved support for 16-bit machines (we hope). + code now compiles unmodified as both ANSI C and C++. + numbers in bases other than 10 are converted using strtoul. + new -f option in Lua to support #! scripts. + luac can now combine text and binaries. * Changes from version 3.1 to 3.2 ------------------------------- + redirected all output in Lua's core to _ERRORMESSAGE and _ALERT. + increased limit on the number of constants and globals per function (from 2^16 to 2^24). + debugging info (lua_debug and hooks) moved into lua_state and new API functions provided to get and set this info. + new debug lib gives full debugging access within Lua. + new table functions "foreachi", "sort", "tinsert", "tremove", "getn". + new io functions "flush", "seek". * Changes from version 3.0 to 3.1 ------------------------------- + NEW FEATURE: anonymous functions with closures (via "upvalues"). + new syntax: - local variables in chunks. - better scope control with DO block END. - constructors can now be also written: { record-part; list-part }. - more general syntax for function calls and lvalues, e.g.: f(x).y=1 o:f(x,y):g(z) f"string" is sugar for f("string") + strings may now contain arbitrary binary data (e.g., embedded zeros). + major code re-organization and clean-up; reduced module interdependecies. + no arbitrary limits on the total number of constants and globals. + support for multiple global contexts. + better syntax error messages. + new traversal functions "foreach" and "foreachvar". + the default for numbers is now double. changing it to use floats or longs is easy. + complete debug information stored in pre-compiled chunks. + sample interpreter now prompts user when run interactively, and also handles control-C interruptions gracefully. * Changes from version 2.5 to 3.0 ------------------------------- + NEW CONCEPT: "tag methods". Tag methods replace fallbacks as the meta-mechanism for extending the semantics of Lua. Whereas fallbacks had a global nature, tag methods work on objects having the same tag (e.g., groups of tables). Existing code that uses fallbacks should work without change. + new, general syntax for constructors {[exp] = exp, ... }. + support for handling variable number of arguments in functions (varargs). + support for conditional compilation ($if ... $else ... $end). + cleaner semantics in API simplifies host code. + better support for writing libraries (auxlib.h). + better type checking and error messages in the standard library. + luac can now also undump. * Changes from version 2.4 to 2.5 ------------------------------- + io and string libraries are now based on pattern matching; the old libraries are still available for compatibility + dofile and dostring can now return values (via return statement) + better support for 16- and 64-bit machines + expanded documentation, with more examples * Changes from version 2.2 to 2.4 ------------------------------- + external compiler creates portable binary files that can be loaded faster + interface for debugging and profiling + new "getglobal" fallback + new functions for handling references to Lua objects + new functions in standard lib + only one copy of each string is stored + expanded documentation, with more examples * Changes from version 2.1 to 2.2 ------------------------------- + functions now may be declared with any "lvalue" as a name + garbage collection of functions + support for pipes * Changes from version 1.1 to 2.1 ------------------------------- + object-oriented support + fallbacks + simplified syntax for tables + many internal improvements (end of HISTORY) |
From: John L. <jr...@us...> - 2005-06-06 23:06:24
|
Update of /cvsroot/wxlua/wxLua/modules/lua/include In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/include Added Files: lauxlib.h lua.h lualib.h luathread.h Log Message: moved files to the modules directory structure --- NEW FILE: lualib.h --- /* ** $Id: lualib.h,v 1.1 2005/06/06 23:06:15 jrl1 Exp $ ** Lua standard libraries ** See Copyright Notice in lua.h */ #ifndef lualib_h #define lualib_h #include "lua.h" #ifndef LUALIB_API #define LUALIB_API LUA_API #endif #define LUA_COLIBNAME "coroutine" LUALIB_API int luaopen_base (lua_State *L); #define LUA_TABLIBNAME "table" LUALIB_API int luaopen_table (lua_State *L); #define LUA_IOLIBNAME "io" #define LUA_OSLIBNAME "os" LUALIB_API int luaopen_io (lua_State *L); #define LUA_STRLIBNAME "string" LUALIB_API int luaopen_string (lua_State *L); #define LUA_MATHLIBNAME "math" LUALIB_API int luaopen_math (lua_State *L); #define LUA_DBLIBNAME "debug" LUALIB_API int luaopen_debug (lua_State *L); LUALIB_API int luaopen_loadlib (lua_State *L); /* to help testing the libraries */ #ifndef lua_assert #define lua_assert(c) /* empty */ #endif /* compatibility code */ #define lua_baselibopen luaopen_base #define lua_tablibopen luaopen_table #define lua_iolibopen luaopen_io #define lua_strlibopen luaopen_string #define lua_mathlibopen luaopen_math #define lua_dblibopen luaopen_debug #endif --- NEW FILE: lauxlib.h --- /* ** $Id: lauxlib.h,v 1.1 2005/06/06 23:06:15 jrl1 Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ #ifndef lauxlib_h #define lauxlib_h #include <stddef.h> #include <stdio.h> #include "lua.h" #ifndef LUALIB_API #define LUALIB_API LUA_API #endif typedef struct luaL_reg { const char *name; lua_CFunction func; } luaL_reg; LUALIB_API void luaL_openlib (lua_State *L, const char *libname, const luaL_reg *l, int nup); LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *e); LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *e); LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname); LUALIB_API int luaL_argerror (lua_State *L, int numarg, const char *extramsg); LUALIB_API const char *luaL_checklstring (lua_State *L, int numArg, size_t *l); LUALIB_API const char *luaL_optlstring (lua_State *L, int numArg, const char *def, size_t *l); LUALIB_API lua_Number luaL_checknumber (lua_State *L, int numArg); LUALIB_API lua_Number luaL_optnumber (lua_State *L, int nArg, lua_Number def); LUALIB_API void luaL_checkstack (lua_State *L, int sz, const char *msg); LUALIB_API void luaL_checktype (lua_State *L, int narg, int t); LUALIB_API void luaL_checkany (lua_State *L, int narg); LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname); LUALIB_API void luaL_getmetatable (lua_State *L, const char *tname); LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname); LUALIB_API void luaL_where (lua_State *L, int lvl); LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...); LUALIB_API int luaL_findstring (const char *st, const char *const lst[]); LUALIB_API int luaL_ref (lua_State *L, int t); LUALIB_API void luaL_unref (lua_State *L, int t, int ref); LUALIB_API int luaL_getn (lua_State *L, int t); LUALIB_API void luaL_setn (lua_State *L, int t, int n); LUALIB_API int luaL_loadfile (lua_State *L, const char *filename); LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name); /* ** =============================================================== ** some useful macros ** =============================================================== */ #define luaL_argcheck(L, cond,numarg,extramsg) if (!(cond)) \ luaL_argerror(L, numarg,extramsg) #define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) #define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) #define luaL_checkint(L,n) ((int)luaL_checknumber(L, n)) #define luaL_checklong(L,n) ((long)luaL_checknumber(L, n)) #define luaL_optint(L,n,d) ((int)luaL_optnumber(L, n,(lua_Number)(d))) #define luaL_optlong(L,n,d) ((long)luaL_optnumber(L, n,(lua_Number)(d))) /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ #ifndef LUAL_BUFFERSIZE #define LUAL_BUFFERSIZE BUFSIZ #endif typedef struct luaL_Buffer { char *p; /* current position in buffer */ int lvl; /* number of strings in the stack (level) */ lua_State *L; char buffer[LUAL_BUFFERSIZE]; } luaL_Buffer; #define luaL_putchar(B,c) \ ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ (*(B)->p++ = (char)(c))) #define luaL_addsize(B,n) ((B)->p += (n)) LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B); LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B); LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l); LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s); LUALIB_API void luaL_addvalue (luaL_Buffer *B); LUALIB_API void luaL_pushresult (luaL_Buffer *B); /* }====================================================== */ /* ** Compatibility macros and functions */ LUALIB_API int lua_dofile (lua_State *L, const char *filename); LUALIB_API int lua_dostring (lua_State *L, const char *str); LUALIB_API int lua_dobuffer (lua_State *L, const char *buff, size_t sz, const char *n); #define luaL_check_lstr luaL_checklstring #define luaL_opt_lstr luaL_optlstring #define luaL_check_number luaL_checknumber #define luaL_opt_number luaL_optnumber #define luaL_arg_check luaL_argcheck #define luaL_check_string luaL_checkstring #define luaL_opt_string luaL_optstring #define luaL_check_int luaL_checkint #define luaL_check_long luaL_checklong #define luaL_opt_int luaL_optint #define luaL_opt_long luaL_optlong #endif --- NEW FILE: lua.h --- /* ** $Id: lua.h,v 1.1 2005/06/06 23:06:15 jrl1 Exp $ ** Lua - An Extensible Extension Language ** Tecgraf: Computer Graphics Technology Group, PUC-Rio, Brazil ** http://www.lua.org mailto:in...@lu... ** See Copyright Notice at the end of this file */ #ifndef lua_h #define lua_h #include <stdarg.h> #include <stddef.h> #define LUA_VERSION "Lua 5.0.2" #define LUA_COPYRIGHT "Copyright (C) 1994-2004 Tecgraf, PUC-Rio" #define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" /* option for multiple returns in `lua_pcall' and `lua_call' */ #define LUA_MULTRET (-1) /* ** pseudo-indices */ #define LUA_REGISTRYINDEX (-10000) #define LUA_GLOBALSINDEX (-10001) #define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) /* error codes for `lua_load' and `lua_pcall' */ #define LUA_ERRRUN 1 #define LUA_ERRFILE 2 #define LUA_ERRSYNTAX 3 #define LUA_ERRMEM 4 #define LUA_ERRERR 5 typedef struct lua_State lua_State; typedef int (*lua_CFunction) (lua_State *L); /* ** functions that read/write blocks when loading/dumping Lua chunks */ typedef const char * (*lua_Chunkreader) (lua_State *L, void *ud, size_t *sz); typedef int (*lua_Chunkwriter) (lua_State *L, const void* p, size_t sz, void* ud); /* ** basic types */ #define LUA_TNONE (-1) #define LUA_TNIL 0 #define LUA_TBOOLEAN 1 #define LUA_TLIGHTUSERDATA 2 #define LUA_TNUMBER 3 #define LUA_TSTRING 4 #define LUA_TTABLE 5 #define LUA_TFUNCTION 6 #define LUA_TUSERDATA 7 #define LUA_TTHREAD 8 /* minimum Lua stack available to a C function */ #define LUA_MINSTACK 20 /* ** generic extra include file */ #ifdef LUA_USER_H #include LUA_USER_H #endif /* type of numbers in Lua */ #ifndef LUA_NUMBER typedef double lua_Number; #else typedef LUA_NUMBER lua_Number; #endif /* mark for all API functions */ #ifndef LUA_API #define LUA_API extern #endif /* ** state manipulation */ LUA_API lua_State *lua_open (void); LUA_API void lua_close (lua_State *L); LUA_API lua_State *lua_newthread (lua_State *L); LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf); /* ** basic stack manipulation */ LUA_API int lua_gettop (lua_State *L); LUA_API void lua_settop (lua_State *L, int idx); LUA_API void lua_pushvalue (lua_State *L, int idx); LUA_API void lua_remove (lua_State *L, int idx); LUA_API void lua_insert (lua_State *L, int idx); LUA_API void lua_replace (lua_State *L, int idx); LUA_API int lua_checkstack (lua_State *L, int sz); LUA_API void lua_xmove (lua_State *from, lua_State *to, int n); /* ** access functions (stack -> C) */ LUA_API int lua_isnumber (lua_State *L, int idx); LUA_API int lua_isstring (lua_State *L, int idx); LUA_API int lua_iscfunction (lua_State *L, int idx); LUA_API int lua_isuserdata (lua_State *L, int idx); LUA_API int lua_type (lua_State *L, int idx); LUA_API const char *lua_typename (lua_State *L, int tp); LUA_API int lua_equal (lua_State *L, int idx1, int idx2); LUA_API int lua_rawequal (lua_State *L, int idx1, int idx2); LUA_API int lua_lessthan (lua_State *L, int idx1, int idx2); LUA_API lua_Number lua_tonumber (lua_State *L, int idx); LUA_API int lua_toboolean (lua_State *L, int idx); LUA_API const char *lua_tostring (lua_State *L, int idx); LUA_API size_t lua_strlen (lua_State *L, int idx); LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx); LUA_API void *lua_touserdata (lua_State *L, int idx); LUA_API lua_State *lua_tothread (lua_State *L, int idx); LUA_API const void *lua_topointer (lua_State *L, int idx); /* ** push functions (C -> stack) */ LUA_API void lua_pushnil (lua_State *L); LUA_API void lua_pushnumber (lua_State *L, lua_Number n); LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t l); LUA_API void lua_pushstring (lua_State *L, const char *s); LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp); LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...); LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); LUA_API void lua_pushboolean (lua_State *L, int b); LUA_API void lua_pushlightuserdata (lua_State *L, void *p); /* ** get functions (Lua -> stack) */ LUA_API void lua_gettable (lua_State *L, int idx); LUA_API void lua_rawget (lua_State *L, int idx); LUA_API void lua_rawgeti (lua_State *L, int idx, int n); LUA_API void lua_newtable (lua_State *L); LUA_API void *lua_newuserdata (lua_State *L, size_t sz); LUA_API int lua_getmetatable (lua_State *L, int objindex); LUA_API void lua_getfenv (lua_State *L, int idx); /* ** set functions (stack -> Lua) */ LUA_API void lua_settable (lua_State *L, int idx); LUA_API void lua_rawset (lua_State *L, int idx); LUA_API void lua_rawseti (lua_State *L, int idx, int n); LUA_API int lua_setmetatable (lua_State *L, int objindex); LUA_API int lua_setfenv (lua_State *L, int idx); /* ** `load' and `call' functions (load and run Lua code) */ LUA_API void lua_call (lua_State *L, int nargs, int nresults); LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc); LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud); LUA_API int lua_load (lua_State *L, lua_Chunkreader reader, void *dt, const char *chunkname); LUA_API int lua_dump (lua_State *L, lua_Chunkwriter writer, void *data); /* ** coroutine functions */ LUA_API int lua_yield (lua_State *L, int nresults); LUA_API int lua_resume (lua_State *L, int narg); /* ** garbage-collection functions */ LUA_API int lua_getgcthreshold (lua_State *L); LUA_API int lua_getgccount (lua_State *L); LUA_API void lua_setgcthreshold (lua_State *L, int newthreshold); /* ** miscellaneous functions */ LUA_API const char *lua_version (void); LUA_API int lua_error (lua_State *L); LUA_API int lua_next (lua_State *L, int idx); LUA_API void lua_concat (lua_State *L, int n); /* ** =============================================================== ** some useful macros ** =============================================================== */ #define lua_boxpointer(L,u) \ (*(void **)(lua_newuserdata(L, sizeof(void *))) = (u)) #define lua_unboxpointer(L,i) (*(void **)(lua_touserdata(L, i))) #define lua_pop(L,n) lua_settop(L, -(n)-1) #define lua_register(L,n,f) \ (lua_pushstring(L, n), \ lua_pushcfunction(L, f), \ lua_settable(L, LUA_GLOBALSINDEX)) #define lua_pushcfunction(L,f) lua_pushcclosure(L, f, 0) #define lua_isfunction(L,n) (lua_type(L,n) == LUA_TFUNCTION) #define lua_istable(L,n) (lua_type(L,n) == LUA_TTABLE) #define lua_islightuserdata(L,n) (lua_type(L,n) == LUA_TLIGHTUSERDATA) #define lua_isnil(L,n) (lua_type(L,n) == LUA_TNIL) #define lua_isboolean(L,n) (lua_type(L,n) == LUA_TBOOLEAN) #define lua_isnone(L,n) (lua_type(L,n) == LUA_TNONE) #define lua_isnoneornil(L, n) (lua_type(L,n) <= 0) #define lua_pushliteral(L, s) \ lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) /* ** compatibility macros and functions */ LUA_API int lua_pushupvalues (lua_State *L); #define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) #define lua_setglobal(L,s) \ (lua_pushstring(L, s), lua_insert(L, -2), lua_settable(L, LUA_GLOBALSINDEX)) #define lua_getglobal(L,s) \ (lua_pushstring(L, s), lua_gettable(L, LUA_GLOBALSINDEX)) /* compatibility with ref system */ /* pre-defined references */ #define LUA_NOREF (-2) #define LUA_REFNIL (-1) #define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \ (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0)) #define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref)) #define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, ref) /* ** {====================================================================== ** useful definitions for Lua kernel and libraries ** ======================================================================= */ /* formats for Lua numbers */ #ifndef LUA_NUMBER_SCAN #define LUA_NUMBER_SCAN "%lf" #endif #ifndef LUA_NUMBER_FMT #define LUA_NUMBER_FMT "%.14g" #endif /* }====================================================================== */ /* ** {====================================================================== ** Debug API ** ======================================================================= */ /* ** Event codes */ #define LUA_HOOKCALL 0 #define LUA_HOOKRET 1 #define LUA_HOOKLINE 2 #define LUA_HOOKCOUNT 3 #define LUA_HOOKTAILRET 4 /* ** Event masks */ #define LUA_MASKCALL (1 << LUA_HOOKCALL) #define LUA_MASKRET (1 << LUA_HOOKRET) #define LUA_MASKLINE (1 << LUA_HOOKLINE) #define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) typedef struct lua_Debug lua_Debug; /* activation record */ typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar); LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); LUA_API lua_Hook lua_gethook (lua_State *L); LUA_API int lua_gethookmask (lua_State *L); LUA_API int lua_gethookcount (lua_State *L); #define LUA_IDSIZE 60 struct lua_Debug { int event; const char *name; /* (n) */ const char *namewhat; /* (n) `global', `local', `field', `method' */ const char *what; /* (S) `Lua', `C', `main', `tail' */ const char *source; /* (S) */ int currentline; /* (l) */ int nups; /* (u) number of upvalues */ int linedefined; /* (S) */ char short_src[LUA_IDSIZE]; /* (S) */ /* private part */ int i_ci; /* active function */ }; /* }====================================================================== */ /****************************************************************************** * Copyright (C) 1994-2004 Tecgraf, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #endif --- NEW FILE: luathread.h --- #ifndef luathread_h #define luathread_h typedef void (* newthread_handler)(lua_State *L, lua_State *NL); LUA_API void luaX_setnewthreadhandler( newthread_handler handler ); LUA_API newthread_handler luaX_getnewthreadhandler(); typedef void (* freethread_handler)(lua_State *L, lua_State *NL); LUA_API void luaX_setfreethreadhandler( freethread_handler handler ); LUA_API freethread_handler luaX_getfreethreadhandler(); #endif |
From: John L. <jr...@us...> - 2005-06-06 23:06:24
|
Update of /cvsroot/wxlua/wxLua/modules/lua/etc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/modules/lua/etc Added Files: Makefile README bin2c.c compat.lua doall.lua lua.ico lua.magic lua.xpm luser_number.h luser_tests.h min.c noparser.c saconfig.c trace.c Log Message: moved files to the modules directory structure --- NEW FILE: min.c --- /* * min.c -- a minimal Lua interpreter * loads stdin only with minimal error handling. * no interaction, and no standard library, only a "print" function. */ #include <stdio.h> #include "lua.h" static int print(lua_State *L) { int n=lua_gettop(L); int i; for (i=1; i<=n; i++) { if (i>1) printf("\t"); if (lua_isstring(L,i)) printf("%s",lua_tostring(L,i)); else if (lua_isnil(L,i)) printf("%s","nil"); else if (lua_isboolean(L,i)) printf("%s",lua_toboolean(L,i) ? "true" : "false"); else printf("%s:%p",lua_typename(L,lua_type(L,i)),lua_topointer(L,i)); } printf("\n"); return 0; } static const char *getF(lua_State *L, void *ud, size_t *size) { FILE *f=(FILE *)ud; static char buff[512]; if (feof(f)) return NULL; *size=fread(buff,1,sizeof(buff),f); return (*size>0) ? buff : NULL; } int main(void) { lua_State *L=lua_open(); lua_register(L,"print",print); if (lua_load(L,getF,stdin,"=stdin") || lua_pcall(L,0,0,0)) fprintf(stderr,"%s\n",lua_tostring(L,-1)); return 0; } --- NEW FILE: lua.magic --- # Lua precompiled files. Versions 2.3 and 4.1 were never officially released. 0 string \33Lua precompiled chunk for Lua >4 byte 0x23 2.3* >4 byte 0x24 2.4 >4 byte 0x25 2.5 >4 byte 0x30 3.0 >4 byte 0x31 3.1 >4 byte 0x32 3.2 >4 byte 0x40 4.0 >4 byte 0x41 4.1* >4 byte 0x50 5.0 --- NEW FILE: noparser.c --- /* * The code below can be used to make a Lua core that does not contain the * parsing modules (lcode, llex, lparser), which represent 35% of the total core. * You'll only be able to load binary files and strings, precompiled with luac. * (Of course, you'll have to build luac with the original parsing modules!) * * To use this module, simply compile it ("make noparser" does that) and * list its object file before the Lua libraries. The linker should then not * load the parsing modules. To try it, do "make luab". */ #include "llex.h" #include "lparser.h" #include "lzio.h" void luaX_init (lua_State *L) { UNUSED(L); } Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff) { UNUSED(z); UNUSED(buff); lua_pushstring(L,"parser not loaded"); lua_error(L); return NULL; } --- NEW FILE: saconfig.c --- /* sa-config.c -- configuration for stand-alone Lua interpreter * * #define LUA_USERCONFIG to this file * * Here are the features that can be customized using #define: * *** Line edit and history: * #define USE_READLINE to use the GNU readline library. * * To use another library for this, use the code below as a start. * Make sure you #define lua_readline and lua_saveline accordingly. * If you do not #define lua_readline, you'll get a version based on fgets * that uses a static buffer of size MAXINPUT. * * *** Static Lua libraries to be loaded at startup: * #define lua_userinit(L) to a Lua function that loads libraries; typically * #define lua_userinit(L) openstdlibs(L);myinit(L) * or * #define lua_userinit(L) myinit(L) * * Another way is to add the prototypes of the init functions here and * #define LUA_EXTRALIBS accordingly. For example, * #define LUA_EXTRALIBS {"mylib","luaopen_mylib"}, * Note the ending comma! * * *** Prompts: * The stand-alone Lua interpreter uses two prompts: PROMPT and PROMPT2. * PROMPT is the primary prompt, shown when the intepreter is ready to receive * a new statement. PROMPT2 is the secondary prompt, shown while a statement * is being entered but is still incomplete. * * *** Program name: * Error messages usually show argv[0] as a program name. In systems that do * not give a valid string as argv[0], error messages show PROGNAME instead. * * */ #ifdef USE_READLINE /* * This section implements of lua_readline and lua_saveline for lua.c using * the GNU readline and history libraries. It should also work with drop-in * replacements such as editline and libedit (you may have to include * different headers, though). * */ #define lua_readline myreadline #define lua_saveline mysaveline #include <ctype.h> #include <readline/readline.h> #include <readline/history.h> static int myreadline (lua_State *L, const char *prompt) { char *s=readline(prompt); if (s==NULL) return 0; else { lua_pushstring(L,s); lua_pushliteral(L,"\n"); lua_concat(L,2); free(s); return 1; } } static void mysaveline (lua_State *L, const char *s) { const char *p; for (p=s; isspace(*p); p++) ; if (*p!=0) { size_t n=strlen(s)-1; if (s[n]!='\n') add_history(s); else { lua_pushlstring(L,s,n); s=lua_tostring(L,-1); add_history(s); lua_remove(L,-1); } } } #endif --- NEW FILE: lua.ico --- (This appears to be a binary file; contents omitted.) --- NEW FILE: luser_tests.h --- /* ** $Id: luser_tests.h,v 1.1 2005/06/06 23:06:15 jrl1 Exp $ ** Internal Header for Debugging of the Lua Implementation ** See Copyright Notice in lua.h */ #ifndef ltests_h #define ltests_h #include <stdlib.h> #define LUA_DEBUG #define LUA_OPNAMES #undef NDEBUG #include <assert.h> #define lua_assert(c) assert(c) #define check_exp(c,e) (lua_assert(c), (e)) #define api_check(L, o) lua_assert(o) /* to avoid warnings, and to make sure value is really unused */ #define UNUSED(x) (x=0, (void)(x)) /* memory allocator control variables */ extern unsigned long memdebug_numblocks; extern unsigned long memdebug_total; extern unsigned long memdebug_maxmem; extern unsigned long memdebug_memlimit; #define l_realloc(b, os, s) debug_realloc(b, os, s) #define l_free(b, os) debug_realloc(b, os, 0) void *debug_realloc (void *block, size_t oldsize, size_t size); /* test for lock/unlock */ extern int islocked; #define LUA_USERSTATE int * #define getlock(l) (*(cast(LUA_USERSTATE *, l) - 1)) #define lua_userstateopen(l) if (l != NULL) getlock(l) = &islocked; #define lua_lock(l) lua_assert((*getlock(l))++ == 0) #define lua_unlock(l) lua_assert(--(*getlock(l)) == 0) int luaB_opentests (lua_State *L); #define LUA_EXTRALIBS { "tests", luaB_opentests }, /* real main will be defined at `ltests.c' */ int l_main (int argc, char *argv[]); #define main l_main /* change some sizes to give some bugs a chance */ #define LUAL_BUFFERSIZE 27 #define MINSTRTABSIZE 2 #endif --- NEW FILE: lua.xpm --- /* XPM */ static char *magick[] = { /* columns rows colors chars-per-pixel */ "32 32 6 1", " c Gray0", ". c #000000008080", "X c #808080808080", "o c #c0c0c0c0c0c0", "O c Gray100", "+ c None", /* pixels */ "++++++++++++++++++++++++++ooo+++", "++++++++++++++++++++++++oX...Xo+", "++++++++++++++++++++++++X.....X+", "+++++++++++++++++++++++o.......o", "+++++++++XX......XX++++o.......o", "+++++++X............X++o.......o", "+++++o................o+X.....X+", "++++X..................XoX...Xo+", "+++X..............XXX...X+ooo+++", "++o.............XoOOOoX..o++++++", "++..............oOOOOOo...++++++", "+X.............XOOOOOOOX..X+++++", "+..............XOOOOOOOX...+++++", "X..............XOOOOOOOX...X++++", "X...............oOOOOOo....X++++", "................XoOOOoX.....++++", "....XO............XXX.......++++", "....XO......................++++", "....XO.....OX..OX.XOOOo.....++++", "....XO.....OX..OX.OoXXOX....++++", "....XO.....OX..OX....XOX....++++", "X...XO.....OX..OX..OOoOX...X++++", "X...XO.....OX..OX.OX..OX...X++++", "+...XOXXXX.OoXoOX.OXXXOX...+++++", "+X..XOOOOO.XOOXOX.XOOOXo..X+++++", "++........................++++++", "++o......................o++++++", "+++X....................X+++++++", "++++X..................X++++++++", "+++++o................o+++++++++", "+++++++X............X+++++++++++", "+++++++++XX......XX+++++++++++++" }; --- NEW FILE: bin2c.c --- /* * bin2c.c * convert files to byte arrays for automatic loading with lua_dobuffer * Luiz Henrique de Figueiredo (lh...@te...) * 02 Apr 2003 20:44:31 */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> static void dump(FILE* f, int n) { printf("static const unsigned char B%d[]={\n",n); for (n=1;;n++) { int c=getc(f); if (c==EOF) break; printf("%3u,",c); if (n==20) { putchar('\n'); n=0; } } printf("\n};\n\n"); } static void fdump(const char* fn, int n) { FILE* f= fopen(fn,"rb"); /* must open in binary mode */ if (f==NULL) { fprintf(stderr,"bin2c: cannot open "); perror(fn); exit(1); } else { printf("/* %s */\n",fn); dump(f,n); fclose(f); } } static void emit(const char* fn, int n) { printf(" lua_dobuffer(L,(const char*)B%d,sizeof(B%d),\"%s\");\n",n,n,fn); } int main(int argc, char* argv[]) { printf("/* code automatically generated by bin2c -- DO NOT EDIT */\n"); printf("{\n"); if (argc<2) { dump(stdin,0); emit("=stdin",0); } else { int i; printf("/* #include'ing this file in a C program is equivalent to calling\n"); for (i=1; i<argc; i++) printf(" lua_dofile(L,\"%s\");\n",argv[i]); printf("*/\n"); for (i=1; i<argc; i++) fdump(argv[i],i); for (i=1; i<argc; i++) emit(argv[i],i); } printf("}\n"); return 0; } --- NEW FILE: doall.lua --- -- emulate the command line behaviour of Lua 4.0 -- usage: lua doall.lua f1.lua f2.lua f3.lua ... for i=1,table.getn(arg) do dofile(arg[i]) end --- NEW FILE: trace.c --- /* * trace.c -- a simple execution tracer for Lua */ #include <stdio.h> #include <string.h> #include "lua.h" #include "lualib.h" #include "lauxlib.h" static FILE* LOG; /* log file */ static int I=0; /* indentation level */ static void hook(lua_State *L, lua_Debug *ar) { const char* s=""; switch (ar->event) { case LUA_HOOKTAILRET: ar->event=LUA_HOOKRET; case LUA_HOOKRET: s="return"; break; case LUA_HOOKCALL: s="call"; break; case LUA_HOOKLINE: s="line"; break; default: break; } fprintf(LOG,"[%d]\t%*s%s\t-- %d\n",I,I,"",s,ar->currentline); if (ar->event==LUA_HOOKCALL) ++I; else if (ar->event==LUA_HOOKRET) --I; } static void start_trace(lua_State *L, FILE* logfile) { lua_sethook(L,hook,LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE, 0); LOG=logfile; } static void stop_trace(lua_State *L) { lua_sethook(L,NULL,0,0); fclose(LOG); } int main(void) { int rc; lua_State *L=lua_open(); lua_baselibopen(L); lua_tablibopen(L); lua_iolibopen(L); lua_strlibopen(L); lua_mathlibopen(L); lua_dblibopen(L); start_trace(L,stderr); rc=lua_dofile(L,NULL); stop_trace(L); return rc; } --- NEW FILE: Makefile --- # makefile for Lua etc LUA= .. include $(LUA)/config LIBLUA=$(LIB)/liblua.a ALL= bin2c min trace noparser luab all: @echo 'choose a target:' $(ALL) bin2c: bin2c.c $(CC) $(CFLAGS) -o $@ $@.c min: min.c $(LIBLUA) $(CC) $(CFLAGS) -o $@ $@.c -L$(LIB) -llua trace: trace.c $(LIBLUA) $(CC) -g $(CFLAGS) -o $@ $@.c -L$(LIB) -llua -llualib $(EXTRA_LIBS) noparser: noparser.c $(CC) $(CFLAGS) -I$(LUA)/src -o $@.o -c $@.c luab: noparser $(LIBLUA) cc -o $@ noparser.o $(LUA)/src/lua/lua.o -L$(LIB) -llua -llualib $(EXTRA_LIBS) $(BIN)/luac $(LUA)/test/hello.lua $@ luac.out -$@ -e'a=1' flat: cd ..; mkdir flat; mv include/*.h src/*.[ch] src/*/*.[ch] flat $(LIBLUA): cd ../src; $(MAKE) clean: rm -f $(ALL) a.out core *.o luac.out luser_tests.h: RCS/ltests.h,v co -q -M ltests.h mv -f ltests.h $@ --- NEW FILE: luser_number.h --- /* luser_number.h -- number type configuration for Lua core * * #define LUA_USER_H to this file and #define one of USE_* below */ #ifdef USE_DOUBLE #define LUA_NUMBER double #define LUA_NUMBER_SCAN "%lf" #define LUA_NUMBER_FMT "%.14g" #endif #ifdef USE_FLOAT #define LUA_NUMBER float #define LUA_NUMBER_SCAN "%f" #define LUA_NUMBER_FMT "%.5g" #endif #ifdef USE_LONG #define LUA_NUMBER long #define LUA_NUMBER_SCAN "%ld" #define LUA_NUMBER_FMT "%ld" #define lua_str2number(s,p) strtol((s), (p), 10) #endif #ifdef USE_INT #define LUA_NUMBER int #define LUA_NUMBER_SCAN "%d" #define LUA_NUMBER_FMT "%d" #define lua_str2number(s,p) ((int) strtol((s), (p), 10)) #endif #ifdef USE_FASTROUND #define lua_number2int(i,d) __asm__("fldl %1\nfistpl %0":"=m"(i):"m"(d)) #endif --- NEW FILE: README --- This directory contains some useful files and code. Unlike the code in ../src, everything here is in the public domain. bin2c.c This program converts files to byte arrays that are automatically run with lua_dobuffer. This allows C programs to include all necessary Lua code, even in precompiled form. Even if the code is included in source form, bin2c is useful because it avoids the hassle of having to quote special characters in C strings. Example of usage: Run bin2c file1 file2 ... > init.h. Then, in your C program, just do #include "init.h" anywhere in the *body* of a function. This will be equivalent to calling lua_dofile(L,"file1"); lua_dofile(L,"file2"); ... Note that the Lua state is called "L". If you use a different name, say "mystate", just #define L mystate before you #include "init.h". compat.lua A compatibility module for Lua 4.0 functions. doall.lua Emulate the command line behaviour of Lua 4.0 lua.ico A Lua icon for Windows. Drawn by hand by Markus Gritsch <gr...@iu...>. lua.magic Data for teaching file(1) about Lua precompiled chunks. lua.xpm The same icon as lua.ico, but in XPM format. It was converted with ImageMagick by Andy Tai <an...@ex...>. luser_number.h Number type configuration for Lua core. luser_tests.h Self-test configuration for Lua core. min.c A minimal Lua interpreter. Good for learning and for starting your own. noparser.c Linking with noparser.o avoids loading the parsing modules in lualib.a. Do "make luab" to build a sample Lua intepreter that does not parse Lua programs, only loads precompiled programs. saconfig.c Configuration for Lua interpreter. trace.c A simple execution tracer. An example of how to use the debug hooks in C. --- NEW FILE: compat.lua --- ------------------------------------------------------------------- -- Real globals -- _ALERT -- _ERRORMESSAGE -- _VERSION -- _G -- assert -- error -- metatable -- next -- print -- require -- tonumber -- tostring -- type -- unpack ------------------------------------------------------------------- -- collectgarbage -- gcinfo -- globals -- call -> protect(f, err) -- loadfile -- loadstring -- rawget -- rawset -- getargs = Main.getargs ?? function do_ (f, err) if not f then print(err); return end local a,b = pcall(f) if not a then print(b); return nil else return b or true end end function dostring(s) return do_(loadstring(s)) end -- function dofile(s) return do_(loadfile(s)) end ------------------------------------------------------------------- -- Table library local tab = table foreach = tab.foreach foreachi = tab.foreachi getn = tab.getn tinsert = tab.insert tremove = tab.remove sort = tab.sort ------------------------------------------------------------------- -- Debug library local dbg = debug getinfo = dbg.getinfo getlocal = dbg.getlocal setcallhook = function () error"`setcallhook' is deprecated" end setlinehook = function () error"`setlinehook' is deprecated" end setlocal = dbg.setlocal ------------------------------------------------------------------- -- math library local math = math abs = math.abs acos = function (x) return math.deg(math.acos(x)) end asin = function (x) return math.deg(math.asin(x)) end atan = function (x) return math.deg(math.atan(x)) end atan2 = function (x,y) return math.deg(math.atan2(x,y)) end ceil = math.ceil cos = function (x) return math.cos(math.rad(x)) end deg = math.deg exp = math.exp floor = math.floor frexp = math.frexp ldexp = math.ldexp log = math.log log10 = math.log10 max = math.max min = math.min mod = math.mod PI = math.pi --??? pow = math.pow rad = math.rad random = math.random randomseed = math.randomseed sin = function (x) return math.sin(math.rad(x)) end sqrt = math.sqrt tan = function (x) return math.tan(math.rad(x)) end ------------------------------------------------------------------- -- string library local str = string strbyte = str.byte strchar = str.char strfind = str.find format = str.format gsub = str.gsub strlen = str.len strlower = str.lower strrep = str.rep strsub = str.sub strupper = str.upper ------------------------------------------------------------------- -- os library clock = os.clock date = os.date difftime = os.difftime execute = os.execute --? exit = os.exit getenv = os.getenv remove = os.remove rename = os.rename setlocale = os.setlocale time = os.time tmpname = os.tmpname ------------------------------------------------------------------- -- compatibility only getglobal = function (n) return _G[n] end setglobal = function (n,v) _G[n] = v end ------------------------------------------------------------------- local io, tab = io, table -- IO library (files) _STDIN = io.stdin _STDERR = io.stderr _STDOUT = io.stdout _INPUT = io.stdin _OUTPUT = io.stdout seek = io.stdin.seek -- sick ;-) tmpfile = io.tmpfile closefile = io.close openfile = io.open function flush (f) if f then f:flush() else _OUTPUT:flush() end end function readfrom (name) if name == nil then local f, err, cod = io.close(_INPUT) _INPUT = io.stdin return f, err, cod else local f, err, cod = io.open(name, "r") _INPUT = f or _INPUT return f, err, cod end end function writeto (name) if name == nil then local f, err, cod = io.close(_OUTPUT) _OUTPUT = io.stdout return f, err, cod else local f, err, cod = io.open(name, "w") _OUTPUT = f or _OUTPUT return f, err, cod end end function appendto (name) local f, err, cod = io.open(name, "a") _OUTPUT = f or _OUTPUT return f, err, cod end function read (...) local f = _INPUT if type(arg[1]) == 'userdata' then f = tab.remove(arg, 1) end return f:read(unpack(arg)) end function write (...) local f = _OUTPUT if type(arg[1]) == 'userdata' then f = tab.remove(arg, 1) end return f:write(unpack(arg)) end |
Update of /cvsroot/wxlua/wxLua/lua/test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/lua/test Removed Files: README bisect.lua cf.lua compat.lua echo.lua env.lua factorial.lua fib.lua fibfor.lua globals.lua hello.lua life.lua luac.lua printf.lua readonly.lua sieve.lua sort.lua table.lua trace-calls.lua trace-globals.lua undefined.lua xd.lua Log Message: moved files to the modules directory structure --- trace-calls.lua DELETED --- --- hello.lua DELETED --- --- sieve.lua DELETED --- --- echo.lua DELETED --- --- xd.lua DELETED --- --- trace-globals.lua DELETED --- --- globals.lua DELETED --- --- life.lua DELETED --- --- table.lua DELETED --- --- undefined.lua DELETED --- --- printf.lua DELETED --- --- sort.lua DELETED --- --- cf.lua DELETED --- --- fibfor.lua DELETED --- --- fib.lua DELETED --- --- factorial.lua DELETED --- --- luac.lua DELETED --- --- bisect.lua DELETED --- --- env.lua DELETED --- --- README DELETED --- --- compat.lua DELETED --- --- readonly.lua DELETED --- |
From: John L. <jr...@us...> - 2005-06-06 23:06:21
|
Update of /cvsroot/wxlua/wxLua/lua/src/luac In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/lua/src/luac Removed Files: Makefile README luac.c luac.dsp print.c Log Message: moved files to the modules directory structure --- README DELETED --- --- luac.dsp DELETED --- --- Makefile DELETED --- --- luac.c DELETED --- --- print.c DELETED --- |
Update of /cvsroot/wxlua/wxLua/lua/src/lib In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/lua/src/lib Removed Files: Makefile README lauxlib.c lbaselib.c ldblib.c liolib.c lmathlib.c loadlib.c lstrlib.c ltablib.c Log Message: moved files to the modules directory structure --- liolib.c DELETED --- --- lmathlib.c DELETED --- --- ltablib.c DELETED --- --- lstrlib.c DELETED --- --- lauxlib.c DELETED --- --- README DELETED --- --- ldblib.c DELETED --- --- lbaselib.c DELETED --- --- Makefile DELETED --- --- loadlib.c DELETED --- |
From: John L. <jr...@us...> - 2005-06-06 23:06:21
|
Update of /cvsroot/wxlua/wxLua/lua/src/lua In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/lua/src/lua Removed Files: Makefile README lua.c lua.dsp Log Message: moved files to the modules directory structure --- README DELETED --- --- lua.dsp DELETED --- --- Makefile DELETED --- --- lua.c DELETED --- |
Update of /cvsroot/wxlua/wxLua/lua/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/lua/src Removed Files: Makefile README lapi.c lapi.h lcode.c lcode.h ldebug.c ldebug.h ldllmain.c ldo.c ldo.h ldump.c lfunc.c lfunc.h lgc.c lgc.h llex.c llex.h llimits.h lmem.c lmem.h lobject.c lobject.h lopcodes.c lopcodes.h lparser.c lparser.h lstate.c lstate.h lstring.c lstring.h ltable.c ltable.h ltests.c ltm.c ltm.h luadll.rc lundump.c lundump.h lvm.c lvm.h lzio.c lzio.h makefile.b32 Log Message: moved files to the modules directory structure --- ltm.c DELETED --- --- lmem.c DELETED --- --- Makefile DELETED --- --- lmem.h DELETED --- --- ldump.c DELETED --- --- ltable.h DELETED --- --- ldebug.h DELETED --- --- ltable.c DELETED --- --- ldebug.c DELETED --- --- lobject.h DELETED --- --- lundump.c DELETED --- --- lundump.h DELETED --- --- lopcodes.h DELETED --- --- lopcodes.c DELETED --- --- lfunc.c DELETED --- --- luadll.rc DELETED --- --- lstate.h DELETED --- --- lgc.c DELETED --- --- README DELETED --- --- lfunc.h DELETED --- --- lgc.h DELETED --- --- lstate.c DELETED --- --- llex.h DELETED --- --- llex.c DELETED --- --- lcode.h DELETED --- --- lcode.c DELETED --- --- lstring.h DELETED --- --- lzio.c DELETED --- --- makefile.b32 DELETED --- --- ldo.h DELETED --- --- lparser.h DELETED --- --- ltm.h DELETED --- --- ldllmain.c DELETED --- --- lzio.h DELETED --- --- lstring.c DELETED --- --- lparser.c DELETED --- --- ldo.c DELETED --- --- lvm.h DELETED --- --- lapi.c DELETED --- --- llimits.h DELETED --- --- lapi.h DELETED --- --- lvm.c DELETED --- --- lobject.c DELETED --- --- ltests.c DELETED --- |
From: John L. <jr...@us...> - 2005-06-06 23:06:21
|
Update of /cvsroot/wxlua/wxLua/lua/doc In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14733/wxLua/lua/doc Removed Files: contents.html logo.gif lua.1 lua.html luac.1 luac.html manual.html readme.html Log Message: moved files to the modules directory structure --- luac.html DELETED --- --- luac.1 DELETED --- --- contents.html DELETED --- --- lua.html DELETED --- --- readme.html DELETED --- --- lua.1 DELETED --- --- logo.gif DELETED --- --- manual.html DELETED --- |