aboutsummaryrefslogtreecommitdiff
path: root/engines/sword25/script/luabindhelper.cpp
blob: 1e68152926e31b0e59a1943fed0010ad8fb9815d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// -----------------------------------------------------------------------------
// This file is part of Broken Sword 2.5
// Copyright (c) Malte Thiesen, Daniel Queteschiner and Michael Elsd�rfer
//
// Broken Sword 2.5 is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Broken Sword 2.5 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Broken Sword 2.5; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------

#include "sword25/kernel/kernel.h"
#include "sword25/script/luabindhelper.h"
#include "sword25/script/luascript.h"
#include <sstream>

#define BS_LOG_PREFIX "LUABINDHELPER"

// -----------------------------------------------------------------------------

namespace
{
	const char * METATABLES_TABLE_NAME = "__METATABLES";
	const char * PERMANENTS_TABLE_NAME = "Permanents";

	bool RegisterPermanent(lua_State * L, const std::string & Name)
	{
		// Eine C-Funktion muss auf dem Stack liegen.
		if (!lua_iscfunction(L, -1)) return false;

		// Sicherstellen, dass die Permanents-Tabelle oben auf dem Stack liegt.
		lua_getfield(L, LUA_REGISTRYINDEX, PERMANENTS_TABLE_NAME);
		if (lua_isnil(L, -1))
		{
			// Permanents-Tabelle existiert noch nicht, sie muss erstellt werden.

			// Nil vom Stack poppen.
			lua_pop(L, 1);

			// Permanents-Tabelle erstellen und eine zweite Referenz darauf auf den Stack legen.
			lua_newtable(L);
			lua_pushvalue(L, -1);

			// Permanents-Tabelle in der Registry speichern. Die zweite Referenz verbleibt auf dem Stack um im Anschluss benutzt zu werden.
			lua_setfield(L, LUA_REGISTRYINDEX, PERMANENTS_TABLE_NAME);
		}

		// C-Funktion mit dem Namen als Index in der Permanents-Tabelle ablegen.
		lua_insert(L, -2);
		lua_setfield(L, -2, Name.c_str());

		// Permanents-Tabelle vom Stack nehmen.
		lua_pop(L, 1);

		return true;
	}
}

// -----------------------------------------------------------------------------

bool BS_LuaBindhelper::AddFunctionsToLib(lua_State * L, const std::string & LibName, const luaL_reg * Functions)
{
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// Wenn der Tabellenname leer ist, werden die Funktionen zum globalen Namensraum hinzugef�gt.
	if (LibName.size() == 0)
	{
		for (; Functions->name; ++Functions)
		{
			lua_pushstring(L, Functions->name);
			lua_pushcclosure(L, Functions->func, 0);
			lua_settable(L, LUA_GLOBALSINDEX);

			// Funktion als permanent registrieren, damit sie beim Persistieren ignoriert wird.
			lua_pushstring(L, Functions->name);
			lua_gettable(L, LUA_GLOBALSINDEX);
			RegisterPermanent(L, Functions->name);
		}
	}
	// Wenn der Tabellenname nicht leer ist, werden die Funktionen zu dieser Tabelle hinzugef�gt.
	else
	{
		// Sicherstellen, dass die Library-Table existiert.
		if (!_CreateTable(L, LibName)) return false;

		// Die einzelnen Funktionen in der Table registrieren.
		for (; Functions->name; ++Functions)
		{
			// Funktion registrieren.
			lua_pushstring(L, Functions->name);
			lua_pushcclosure(L, Functions->func, 0);
			lua_settable(L, -3);

			// Funktion als permanent registrieren, damit sie beim Persistieren ignoriert wird.
			lua_pushstring(L, Functions->name);
			lua_gettable(L, -2);
			RegisterPermanent(L, LibName + "." + Functions->name);
		}

		// Library-Table vom Lua-Stack nehmen.
		lua_pop(L, 1);
	}
	

#ifdef DEBUG
	BS_ASSERT(__startStackDepth == lua_gettop(L));
#endif

	return true;
}

// -----------------------------------------------------------------------------

bool BS_LuaBindhelper::AddConstantsToLib(lua_State * L, const std::string & LibName, const lua_constant_reg * Constants)
{
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// Wenn der Tabellenname leer ist, werden die Konstanten zum globalen Namensraum hinzugef�gt.
	if (LibName.size() == 0)
	{
		for (; Constants->Name; ++Constants)
		{
			lua_pushstring(L, Constants->Name);
			lua_pushnumber(L, Constants->Value);
			lua_settable(L, LUA_GLOBALSINDEX);
		}
	}
	// Wenn der Tabellenname nicht leer ist, werden die Konstanten zu dieser Tabelle hinzugef�gt.
	else
	{
		// Sicherstellen, dass die Library-Table existiert.
		if (!_CreateTable(L, LibName)) return false;
		
		// Die einzelnen Konstanten in der Table registrieren
		for (; Constants->Name; ++Constants)
		{
			lua_pushstring(L, Constants->Name);
			lua_pushnumber(L, Constants->Value);
			lua_settable(L, -3);
		}

		// Library-Tabelle vom Lua-Stack nehmen
		lua_pop(L, 1);
	}

#ifdef DEBUG
	BS_ASSERT(__startStackDepth == lua_gettop(L));
#endif

	return true;
}

// -----------------------------------------------------------------------------

bool BS_LuaBindhelper::AddMethodsToClass(lua_State * L, const std::string & ClassName, const luaL_reg * Methods)
{
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// Metatable auf den Lua-Stack laden
	if (!GetMetatable(L, ClassName)) return false;
	
	// Die einzelnen Methoden in der Metatable registrieren
	for (; Methods->name; ++Methods)
	{
		lua_pushstring(L, Methods->name);
		lua_pushcclosure(L, Methods->func, 0);
		lua_settable(L, -3);

		// Funktion als permanent registrieren, damit sie beim Persistieren ignoriert wird.
		lua_pushstring(L, Methods->name);
		lua_gettable(L, -2);
		RegisterPermanent(L, ClassName + "." + Methods->name);
	}

	// Metatable vom Lua-Stack nehmen
	lua_pop(L, 1);

#ifdef DEBUG
	BS_ASSERT(__startStackDepth == lua_gettop(L));
#endif

	return true;
}

// -----------------------------------------------------------------------------

bool BS_LuaBindhelper::SetClassGCHandler(lua_State * L, const std::string & ClassName, lua_CFunction GCHandler)
{
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// Metatable auf den Lua-Stack laden
	if (!GetMetatable(L, ClassName)) return false;

	// Den GC-Handler in die Metatable schreiben
	lua_pushstring(L, "__gc");
	lua_pushcclosure(L, GCHandler, 0);
	lua_settable(L, -3);

	// Funktion als permanent registrieren, damit sie beim Persistieren ignoriert wird.
	lua_pushstring(L, "__gc");
	lua_gettable(L, -2);
	RegisterPermanent(L, ClassName + ".__gc");

	// Metatable vom Lua-Stack nehmen
	lua_pop(L, 1);

#ifdef DEBUG
	BS_ASSERT(__startStackDepth == lua_gettop(L));
#endif

	return true;
}

// -----------------------------------------------------------------------------

namespace
{
	void PushMetatableTable(lua_State * L)
	{
		// Tabelle mit den Metatabellen auf den Stack legen.
		lua_getglobal(L, METATABLES_TABLE_NAME);

		// Wenn die Tabelle noch nicht existiert, muss sie erstellt werden.
		if (lua_isnil(L, -1))
		{
			// nil vom Stack poppen.
			lua_pop(L, 1);

			// Neue Tabelle erstellen, in die globale Table eintragen und eine Referenz auf dem Stack lassen.
			lua_newtable(L);
			lua_pushvalue(L, -1);
			lua_setglobal(L, METATABLES_TABLE_NAME);
		}
	}
}


bool BS_LuaBindhelper::GetMetatable(lua_State * L, const std::string & TableName)
{
	// Tabelle mit den Metatabellen auf den Stack legen.
	PushMetatableTable(L);

	// Versuchen, die gew�nschte Metatabelle auf den Stack zu legen. Wenn sie noch nicht existiert, muss sie erstellt werden.
	lua_getfield(L, -1, TableName.c_str());
	if (lua_isnil(L, -1))
	{
		// nil vom Stack poppen.
		lua_pop(L, 1);

		// Neue Tabelle erstellen.
		lua_newtable(L);

		// Das __index Feld der Metatabele zeigt auf die Metatabelle selbst.
		lua_pushvalue(L, -1);
		lua_setfield(L, -2, "__index");

		// Persistfeld auf true setzen. Dies sorgt daf�r, dass Objekte mit dieser Metatabelle direkt gespeichert werden.
		lua_pushbooleancpp(L, true);
		lua_setfield(L, -2, "__persist");

		// Metatabelle in die Tabelle f�r Metatabellen eintragen und eine Referenz auf dem Stack lassen.
		lua_pushvalue(L, -1);
		lua_setfield(L, -3, TableName.c_str());
	}

	// Tabelle mit den Metatabellen vom Stack nehmen.
	lua_remove(L, -2);

	return true;
}

// -----------------------------------------------------------------------------

bool BS_LuaBindhelper::_CreateTable(lua_State * L, const std::string & TableName)
{
	// Der Tabellenname wird an den Punkten auseinandergetrennt und jeweils die Untertabellen erstellt.
	// Auf diese Weise k�nnen auch Tabellen mit Untertabellen erstellt werden (z.B. Foo.Bar).
	std::string::size_type PartBegin = 0;
	while (PartBegin <= TableName.size())
	{
		std::string::size_type PartEnd;
		PartEnd = TableName.find(".", PartBegin);
		if (PartEnd == std::string::npos) PartEnd = TableName.size();
		std::string SubTableName = TableName.substr(PartBegin, PartEnd - PartBegin);

		// Tabellen mit einen leeren String als Namen sind nicht zul�ssig.
		if (SubTableName.size() == 0) return false;

		// �berpr�fen, ob die Tabelle mit dem Namen bereits existiert.
		// Beim ersten Durchgang wird im globalen Namensbereich gesucht, bei sp�teren Durchg�ngen in der entsprechenden Elterntabelle auf dem Stack.
		if (PartBegin == 0)
		{
			lua_pushstring(L, SubTableName.c_str());
			lua_gettable(L, LUA_GLOBALSINDEX);
		}
		else
		{
			lua_pushstring(L, SubTableName.c_str());
			lua_gettable(L, -2);
			if (!lua_isnil(L, -1)) lua_remove(L, -2);
		}

		// Wenn nicht, Table erstellen
		if (lua_isnil(L, -1))
		{
			// nil-Wert vom Stack holen
			lua_pop(L, 1);

			// Neue Tabelle erstellen
			lua_newtable(L);
			lua_pushstring(L, SubTableName.c_str());
			lua_pushvalue(L, -2);
			if (PartBegin == 0)
				lua_settable(L, LUA_GLOBALSINDEX);
			else
			{
				lua_settable(L, -4);
				lua_remove(L, -2);
			}
		}

		PartBegin = PartEnd + 1;
	}

	return true;
}

namespace
{
	std::string GetLuaValueInfo(lua_State * L, int StackIndex)
	{
		switch (lua_type(L, StackIndex))
		{
			case LUA_TNUMBER:
				lua_pushstring(L, lua_tostring(L, StackIndex));
				break;

			case LUA_TSTRING:
				lua_pushfstring(L, "\"%s\"", lua_tostring(L, StackIndex));
				break;

			case LUA_TBOOLEAN:
				lua_pushstring(L, (lua_toboolean(L, StackIndex) ? "true" : "false"));
				break;

			case LUA_TNIL:
				lua_pushliteral(L, "nil");
				break;

			default:
				lua_pushfstring(L, "%s: %p", luaL_typename(L, StackIndex), lua_topointer(L, StackIndex));
				break;
		}

		std::string Result(lua_tostring(L, -1));
		lua_pop(L, 1);

		return Result;
	}
}

std::string BS_LuaBindhelper::StackDump(lua_State *L)
{
	std::ostringstream oss;

	int i = lua_gettop(L);
	oss << "------------------- Stack Dump -------------------\n";

	while(i)
	{
		oss << i << ": " << GetLuaValueInfo(L, i) << "\n";
		i--;
	}

	oss << "-------------- Stack Dump Finished ---------------\n";

	return oss.str();
} 

std::string BS_LuaBindhelper::TableDump(lua_State * L)
{
	std::ostringstream oss;

	oss << "------------------- Table Dump -------------------\n";

	lua_pushnil(L);
	while (lua_next(L, -2) != 0)
	{
		// Der Wert des aktuellen Elementes liegt oben auf dem Stack, darunter der Index.
		oss << GetLuaValueInfo(L, -2) << " : " << GetLuaValueInfo(L, -1) << "\n";

		// Wert vom Stack poppen. Der Index liegt dann oben f�r den n�chsten Aufruf von lua_next().
		lua_pop(L, 1);
	}

	oss << "-------------- Table Dump Finished ---------------\n";

	return oss.str();
}