Lua Utils
Biblioteca utilitária para facilitar a integração de Lua com C++
luaEnv.h
Go to the documentation of this file.
1 /************************************************************************
2 **
3 ** Copyright (C) 2009 K2FS Sistemas e Projetos Ltd.
4 ** All rights reserved.
5 **
6 ************************************************************************/
7 
18 #ifndef _LUAENV_H_
19 #define _LUAENV_H_
20 
21 #include "luaConfig.h"
22 
23 #include <assert.h>
24 #include <QVariant>
25 #include <lua.hpp>
26 
27 #include <QStringList>
28 #include <QSet>
29 
30 #define luaPrintable(string) QString(string).toLatin1().constData()
31 
34 class LUAUTILS_API_EXPORT LuaEnv
35 {
36 public:
37 
40  {
43  STACK_AUTO
44  };
45 
48  {
49  LIB_BASE = 0x01,
50  LIB_TABLE = 0x02,
51  LIB_IO = 0x04,
52  LIB_OS = 0x08,
53  LIB_STRING = 0x10,
54  LIB_MATH = 0x20,
55  LIB_DEBUG = 0x40,
56  LIB_PACKAGE = 0x80,
57  LIB_ALL = 0xFF
58  };
59 
61  typedef luaL_Reg FunctionRegister;
62 
64  typedef void (*RedirectedOutputCb)(void* context, QString str);
65 
69  typedef QString(*ScriptNameFilterCb)(void* context, QString scriptName);
70 
74  LuaEnv() : _l(NULL), _outputCb(NULL), _outputContext(NULL), _envTableRef(LUA_NOREF),
75  _dofileScriptNameFilter(NULL), _dofileScriptNameContext(NULL) {}
76 
78  LuaEnv(lua_State* state) : _l(state), _outputCb(NULL), _outputContext(NULL), _envTableRef(LUA_NOREF),
79  _dofileScriptNameFilter(NULL), _dofileScriptNameContext(NULL) {}
80 
82  ~LuaEnv() {}
83 
84  bool newState(int libOptions = LIB_ALL);
85  void closeState();
86 
87  void removeSymbols(const QStringList& symbolNames);
88 
90  void setState(lua_State* state) { _l = state; }
91 
93  lua_State* state() { return _l; }
94 
96  operator lua_State* () { return _l; }
97 
98  void redirectOutput(RedirectedOutputCb cb, void* context);
99  void replaceDofile(QString table = "", ScriptNameFilterCb scriptNameFilter = NULL, void* scriptNameFilterContext = NULL);
100 
102  void setDofileTable(QString table) { _dofileTable = table; }
103 
104  void setRsrcPath(const QStringList& pathList);
105 
107  const QStringList& rsrcPath() const { return _rsrcPathList; }
108 
109  bool runScript (QString file, QString table, QString& err);
110  bool runRsrcScript (QString file, QString table, QString& err);
111  bool runVerifiedRsrcScript(QString file, QString table, QString hash, bool encoded, QString& err);
112  bool runScriptStr (QString script, QString table, QString& err);
113  bool runScriptStr (QString script, QString table, QString name, QString& err);
114  bool runScriptStr (QByteArray& script, QString table, QString name, QString& err);
115 
122  void setLoadTableEnv(int tableRef = LUA_NOREF) { _envTableRef = tableRef; }
123 
124  void registerFunctions(const FunctionRegister* reg, const char* table = NULL);
125  void registerFunction (const char* globalName, lua_CFunction func, void* userdata_1 = NULL, void* userdata_2 = NULL);
126 
127  QVariant getGlobal(const char* name, StackOption opt = STACK_AUTO);
128 
130  QVariant getGlobal(QString name, StackOption opt = STACK_AUTO) { return getGlobal(luaPrintable(name), opt); }
131 
132  void setGlobal(const char* name, const QVariant& val);
133 
135  void setGlobal(QString name, const QVariant& val) { return setGlobal(luaPrintable(name), val); }
136 
137  QVariant toVariant(StackOption opt, int index = -1);
138 
139  void pushVariant(const QVariant& val);
140 
142  void pop(int num = 1) { assert(_l); lua_pop(_l, num); }
143 
145  int top() { assert(_l); return lua_gettop(_l); }
146 
148  void setTop(int index) { assert(_l); lua_settop(_l, index); }
149 
150  QVariant getLocal(const char* name, StackOption opt = STACK_AUTO);
151 
153  QVariant getLocal(QString name, StackOption opt = STACK_AUTO) { return getLocal(luaPrintable(name), opt); }
154 
155  static bool isIdentifier(QString str);
156  static QString quote(QString str);
157 
158  // Extra space support.
159  // Requires the Lua library to be compiled with additional space added
160  // to the begining of a lua_State through the LUAI_EXTRASPACE macro
161  // This macro should define the size in bytes of the extra sapce and also
162  // be suitably aligned so that an allocated structure + the extra space
163  // ends up being a suitable pointer to a regular Lua state.
164 #ifdef LUAI_EXTRASPACE
165 
167  template <class T> T* extraSpace() const { return extraSpace<T>(_l); }
168 
170  template <class T> static T* extraSpace(lua_State* state)
171  {
172  assert(sizeof(T) <= LUAI_EXTRASPACE);
173  return (T*)((char*)state - LUAI_EXTRASPACE);
174  }
175 
176  // Cancelation support.
177  // Requires the Lua library to be compiled with extra space to store the
178  // per Lua state cancelation flag and also to define the LUAUTILS_CANCEL
179  // macro. This macro also affects method redirectors defined on luaMethod.h
180 #ifdef LUAUTILS_CANCEL
181  static_assert(2 * sizeof(quint32) <= LUAI_EXTRASPACE, "Invalid extra space size to enable cancelation support");
182 
184  bool cancelRequested() const { return cancelRequested(_l); }
185 
187  void setCancelFlag(bool cancel) { setCancelFlag(_l, cancel); }
188 
193  void disableCancelation(bool mode) { disableCancelation(_l, mode); }
194 
196  static bool cancelRequested(lua_State* state) { quint32* p = extraSpace<quint32>(state); return p[0] && !p[1]; }
197 
199  static void setCancelFlag(lua_State* state, bool cancel) { extraSpace<quint32>(state)[0] = cancel; }
200 
205  static void disableCancelation(lua_State* state, bool mode) { extraSpace<quint32>(state)[1] = mode; }
206 #endif
207 #endif
208 
209  static QVariant& clearReferences(QVariant& obj, bool useLists, bool firstLevelIsMap, bool allowFunctions);
210 
211 private:
212  Q_DISABLE_COPY(LuaEnv)
213 
214  void initState(int libOptions);
215  bool loadScriptData(QString file, QByteArray& script, QString& err);
216  bool runScriptAux (QString table, QString& err);
217 
218  static int printCb(lua_State* L);
219  static int dofile (lua_State* L);
220 
221  lua_State* _l;
222 
223  RedirectedOutputCb _outputCb;
227  ScriptNameFilterCb _dofileScriptNameFilter;
230 };
231 
232 
239 class LUAUTILS_API_EXPORT AutoLuaEnv : public LuaEnv
240 {
241 public:
242 
247  AutoLuaEnv(int libOptions = LIB_ALL)
248  {
249  if(!newState(libOptions))
250  throw std::bad_alloc();
251  }
252 
255  {
256  closeState();
257  }
258 };
259 
260 #endif
261 
void setDofileTable(QString table)
Updates the table where dofile functions should be executed.
Definition: luaEnv.h:102
void setLoadTableEnv(int tableRef=LUA_NOREF)
Cadastra referência para uma tabela que será utilizada como ambiente global pelas diversas funções de...
Definition: luaEnv.h:122
LibraryOptions
Opçoes de bibliotecas a serem carregadas na inicialização do estado.
Definition: luaEnv.h:47
void * _dofileScriptNameContext
A user context passed as parameter to _dofileScriptNameFilter.
Definition: luaEnv.h:228
void setTop(int index)
Altera topo da pilha para o indice recebido como parâmetro.
Definition: luaEnv.h:148
Definition: luaEnv.h:239
lua_State * state()
Retorna o estado Lua armazenado.
Definition: luaEnv.h:93
luaL_Reg FunctionRegister
Tipo para tabela de funções a serem registradas no ambiente.
Definition: luaEnv.h:61
lua_State * _l
Lua state associado com este objeto.
Definition: luaEnv.h:221
~AutoLuaEnv()
Destrutor. Fecha o ambiente lua.
Definition: luaEnv.h:254
QVariant getGlobal(QString name, StackOption opt=STACK_AUTO)
Método sobrecarregado recebendo um QString.
Definition: luaEnv.h:130
RedirectedOutputCb _outputCb
Callback usada para redirecionamento de mensganes de output.
Definition: luaEnv.h:223
LuaEnv(lua_State *state)
Construtor. Cria um LuaEnv a partir de um ambiente Lua pré-existente.
Definition: luaEnv.h:78
const QStringList & rsrcPath() const
Retorna lista de paths considerados para carga de resurces por runRsrcScript()
Definition: luaEnv.h:107
void pop(int num=1)
Remove num elementos da pilha.
Definition: luaEnv.h:142
QVariant getLocal(QString name, StackOption opt=STACK_AUTO)
Método sobrecarregado recebendo um QString.
Definition: luaEnv.h:153
void setGlobal(QString name, const QVariant &val)
Método sobrecarregado recebendo um QString.
Definition: luaEnv.h:135
AutoLuaEnv(int libOptions=LIB_ALL)
Construtor. Cria um novo ambiente lua que será destruído junto com o objeto.
Definition: luaEnv.h:247
LuaEnv()
Construtor padrão. Cria objeto com ambiente Lua vazio.
Definition: luaEnv.h:74
~LuaEnv()
Destrutor. Ambiente Lua NÃO é fechado automaticamente.
Definition: luaEnv.h:82
Classe para interface com ambientes Lua.
Definition: luaEnv.h:34
void setState(lua_State *state)
Altera o ambiente Lua armazenado. Ambiente anterior, se existente, NÃO é fechado.
Definition: luaEnv.h:90
Indica que o valor não deve ser removido da pilha.
Definition: luaEnv.h:42
Declaration of usefull configuration definitions and some compatibility options fro compiling with se...
int _envTableRef
Referência para tabela usada como ambiente global na carga de scripts setada por setLoadTableEnv()
Definition: luaEnv.h:229
bool newState(int libOptions=LIB_ALL)
Cria um novo ambiente lua e o inicializa com as funções das bibliotecas especificadas Se a biblioteca...
Definition: luaEnv.cpp:56
void * _outputContext
Contexto passado para a callback.
Definition: luaEnv.h:224
QStringList _rsrcPathList
Lista de paths base usados para leitura de resources.
Definition: luaEnv.h:225
StackOption
Opções de manipulação de pilha.
Definition: luaEnv.h:39
Indica que o valor deve ser removido da pilha.
Definition: luaEnv.h:41
QString _dofileTable
Nome da tabela de ambiente para operações de dofile se este foi substituido por replaceDofile()
Definition: luaEnv.h:226
int top()
Retorna índice do elemento no topo da pilha.
Definition: luaEnv.h:145
void closeState()
Fecha o estado Lua.
Definition: luaEnv.cpp:74
ScriptNameFilterCb _dofileScriptNameFilter
The filter function for script names from the overloaded dofile function.
Definition: luaEnv.h:227