00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031 #ifndef PTLIB_LUA_H
00032 #define PTLIB_LUA_H
00033
00034 #ifdef P_USE_PRAGMA
00035 #pragma interface
00036 #endif
00037
00038 #include <ptlib.h>
00039 #include <ptbuildopts.h>
00040
00041 #if P_LUA
00042
00043 #include <lua.hpp>
00044
00045 #if defined(_MSC_VER)
00046 #pragma comment(lib, P_LUA_LIBRARY)
00047 #endif
00048
00050
00051 class PLua
00052 {
00053 public:
00054 PLua();
00055 ~PLua();
00056
00057 virtual bool LoadString(const char * text);
00058
00059 virtual bool LoadFile(const char * filename);
00060
00061 virtual bool Run(const char * program = NULL);
00062
00063 virtual void OnError(int code, const PString & str);
00064
00065 operator lua_State * () { return m_lua; }
00066
00067 virtual void SetValue(const char * name, const char * value);
00068
00069 virtual void SetFunction(const char * name, lua_CFunction func);
00070
00071 bool CallLuaFunction(const char * name);
00072 bool CallLuaFunction(const char * name, const char * sig, ...);
00073
00074 static int TraceFunction(lua_State * L);
00075
00076 PString GetLastErrorText() const
00077 { return m_lastErrorText; }
00078
00079 protected:
00080 lua_State * m_lua;
00081 PString m_lastErrorText;
00082 };
00083
00084 #define PLUA_BINDING_START(class_type) \
00085 typedef class_type PLua_InstanceType; \
00086 void UnbindFromInstance(PLua &, const char *) { } \
00087 void BindToInstance(PLua & lua, const char * instanceName) \
00088 { \
00089 \
00090 luaL_newmetatable(lua, instanceName); \
00091 lua_pushvalue(lua, -1); \
00092 lua_setfield(lua, -2, "__index"); \
00093
00094 #define PLUA_BINDING2(cpp_name, lua_name) \
00095 \
00096 lua_pushlightuserdata(lua, (void *)this); \
00097 lua_pushcclosure (lua, &PLua_InstanceType::cpp_name##_callback, 1); \
00098 lua_setfield (lua, -2, lua_name); \
00099
00100 #define PLUA_BINDING(fn_name) \
00101 PLUA_BINDING2(fn_name, #fn_name)
00102
00103 #define PLUA_BINDING_END() \
00104 \
00105 lua_newtable(lua); \
00106 luaL_getmetatable(lua, instanceName); \
00107 lua_setmetatable(lua, -2); \
00108 lua_setglobal(lua, instanceName); \
00109 } \
00110
00111 #define PLUA_FUNCTION_DECL(fn_name) \
00112 static int fn_name##_callback(lua_State * L) \
00113 { \
00114 PLua_InstanceType * instance = (PLua_InstanceType *)lua_touserdata(L, lua_upvalueindex(1)); \
00115 return instance->fn_name(L); \
00116 } \
00117
00118 #define PLUA_FUNCTION(fn_name) \
00119 PLUA_FUNCTION_DECL(fn_name) \
00120 int fn_name(lua_State * L) \
00121
00122 #define PLUA_FUNCTION_NOARGS(fn_name) \
00123 PLUA_FUNCTION_DECL(fn_name) \
00124 int fn_name(lua_State *) \
00125
00126 #define PLUA_DECLARE_FUNCTION(fn_name) \
00127 PLUA_FUNCTION_DECL(fn_name) \
00128 int fn_name(lua_State * L); \
00129
00130
00132
00133 #endif // P_LUA
00134
00135 #endif // PTLIB_LUA_H
00136