aboutsummaryrefslogtreecommitdiff
path: root/engines/sword25/script/luabindhelper.cpp
blob: 843e8dd4de8443a74d7a160fabef78e3bd79e8e8 (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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program 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.

 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * $URL$
 * $Id$
 *
 */

/*
 * This code is based on Broken Sword 2.5 engine
 *
 * Copyright (c) Malte Thiesen, Daniel Queteschiner and Michael Elsdoerfer
 *
 * Licensed under GNU GPL v2
 *
 */

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

#include "sword25/kernel/kernel.h"
#include "sword25/script/luabindhelper.h"
#include "sword25/script/luascript.h"

#define BS_LOG_PREFIX "LUABINDHELPER"

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

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

bool RegisterPermanent(lua_State *L, const Common::String &Name) {
	// A C function has to be on the stack
	if (!lua_iscfunction(L, -1)) return false;

	// Make sure that the Permanents-Table is on top of the stack
	lua_getfield(L, LUA_REGISTRYINDEX, PERMANENTS_TABLE_NAME);
	if (lua_isnil(L, -1)) {
		// Permanents-Table does not yet exist, so it has to be created

		// Pop nil from the stack
		lua_pop(L, 1);

		// Create Permanents-Table and insert a second reference to it on the stack
		lua_newtable(L);
		lua_pushvalue(L, -1);

		// Store the Permanents-Table in the registry. The second reference is left
		// on the stack to be used in the connection
		lua_setfield(L, LUA_REGISTRYINDEX, PERMANENTS_TABLE_NAME);
	}

	// C function with the name of an index in the Permanents-Table
	lua_insert(L, -2);
	lua_setfield(L, -2, Name.c_str());

	// Remove the Permanents-Table from the stack
	lua_pop(L, 1);

	return true;
}
}

namespace Sword25 {

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

/**
 * Registers a set of functions into a Lua library.
 * @param L             A pointer to the Lua VM
 * @param LibName       The name of the library.
 * If this is an empty string, the functions will be added to the global namespace.
 * @param Functions     An array of function pointers along with their names.
 * The array must be terminated with the enry (0, 0)
 * @return              Returns true if successful, otherwise false.
 */
bool LuaBindhelper::AddFunctionsToLib(lua_State *L, const Common::String &LibName, const luaL_reg *Functions) {
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// If the table name is empty, the functions are to be added to the global namespace
	if (LibName.size() == 0) {
		for (; Functions->name; ++Functions) {
			lua_pushstring(L, Functions->name);
			lua_pushcclosure(L, Functions->func, 0);
			lua_settable(L, LUA_GLOBALSINDEX);

			// Function is being permanently registed, so persistence can be ignored
			lua_pushstring(L, Functions->name);
			lua_gettable(L, LUA_GLOBALSINDEX);
			RegisterPermanent(L, Functions->name);
		}
	} else { // If the table name is not empty, the functions are added to the given table
		// Ensure that the library table exists
		if (!_CreateTable(L, LibName)) return false;

		// Register each function into the table
		for (; Functions->name; ++Functions) {
			// Function registration
			lua_pushstring(L, Functions->name);
			lua_pushcclosure(L, Functions->func, 0);
			lua_settable(L, -3);

			// Function is being permanently registed, so persistence can be ignored
			lua_pushstring(L, Functions->name);
			lua_gettable(L, -2);
			RegisterPermanent(L, LibName + "." + Functions->name);
		}

		// Remove the library table from the Lua stack
		lua_pop(L, 1);
	}

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

	return true;
}

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

/**
 * Adds a set of constants to the Lua library
 * @param L             A pointer to the Lua VM
 * @param LibName       The name of the library.
 * If this is an empty string, the functions will be added to the global namespace.
 * @param Constants     An array of the constant values along with their names.
 * The array must be terminated with the enry (0, 0)
 * @return              Returns true if successful, otherwise false.
 */
bool LuaBindhelper::AddConstantsToLib(lua_State *L, const Common::String &LibName, const lua_constant_reg *Constants) {
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// If the table is empty, the constants are added to the global namespace
	if (LibName.size() == 0) {
		for (; Constants->Name; ++Constants) {
			lua_pushstring(L, Constants->Name);
			lua_pushnumber(L, Constants->Value);
			lua_settable(L, LUA_GLOBALSINDEX);
		}
	}
	// If the table name is nto empty, the constants are added to that table
	else {
		// Ensure that the library table exists
		if (!_CreateTable(L, LibName)) return false;

		// Register each constant in the table
		for (; Constants->Name; ++Constants) {
			lua_pushstring(L, Constants->Name);
			lua_pushnumber(L, Constants->Value);
			lua_settable(L, -3);
		}

		// Remove the library table from the Lua stack
		lua_pop(L, 1);
	}

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

	return true;
}

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

/**
 * Adds a set of methods to a Lua class
 * @param L             A pointer to the Lua VM
 * @param ClassName     The name of the class
 * When the class name specified does not exist, it is created.
 * @param Methods       An array of function pointers along with their method names.
 * The array must be terminated with the enry (0, 0)
 * @return              Returns true if successful, otherwise false.
 */
bool LuaBindhelper::AddMethodsToClass(lua_State *L, const Common::String &ClassName, const luaL_reg *Methods) {
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// Load the metatable onto the Lua stack
	if (!GetMetatable(L, ClassName)) return false;

	// Register each method in the Metatable
	for (; Methods->name; ++Methods) {
		lua_pushstring(L, Methods->name);
		lua_pushcclosure(L, Methods->func, 0);
		lua_settable(L, -3);

		// Function is being permanently registed, so persistence can be ignored
		lua_pushstring(L, Methods->name);
		lua_gettable(L, -2);
		RegisterPermanent(L, ClassName + "." + Methods->name);
	}

	// Remove the metatable from the stack
	lua_pop(L, 1);

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

	return true;
}

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

/**
 * Sets the garbage collector callback method when items of a particular class are deleted
 * @param L             A pointer to the Lua VM
 * @param ClassName     The name of the class
 * When the class name specified does not exist, it is created.
 * @param GCHandler     A function pointer
 * @return              Returns true if successful, otherwise false.
 */
bool LuaBindhelper::SetClassGCHandler(lua_State *L, const Common::String &ClassName, lua_CFunction GCHandler) {
#ifdef DEBUG
	int __startStackDepth = lua_gettop(L);
#endif

	// Load the metatable onto the Lua stack
	if (!GetMetatable(L, ClassName)) return false;

	// Add the GC handler to the Metatable
	lua_pushstring(L, "__gc");
	lua_pushcclosure(L, GCHandler, 0);
	lua_settable(L, -3);

	// Function is being permanently registed, so persistence can be ignored
	lua_pushstring(L, "__gc");
	lua_gettable(L, -2);
	RegisterPermanent(L, ClassName + ".__gc");

	// Remove the metatable from the stack
	lua_pop(L, 1);

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

	return true;
}

} // End of namespace Sword25

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

namespace {
void PushMetatableTable(lua_State *L) {
	// Push the Metatable table onto the stack
	lua_getglobal(L, METATABLES_TABLE_NAME);

	// If the table doesn't yet exist, it must be created
	if (lua_isnil(L, -1)) {
		// Pop nil from stack
		lua_pop(L, 1);

		// New table has been created, so add it to the global table and leave reference on stack
		lua_newtable(L);
		lua_pushvalue(L, -1);
		lua_setglobal(L, METATABLES_TABLE_NAME);
	}
}
}

namespace Sword25 {

bool LuaBindhelper::GetMetatable(lua_State *L, const Common::String &TableName) {
	// Push the Metatable table onto the stack
	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)) {
		// Pop nil from stack
		lua_pop(L, 1);

		// Create new table
		lua_newtable(L);

		// Set the __index field in the table
		lua_pushvalue(L, -1);
		lua_setfield(L, -2, "__index");

		// Flag the table as persisted. This ensures that objects within this table get stored
		lua_pushbooleancpp(L, true);
		lua_setfield(L, -2, "__persist");

		// Set the table name and push it onto the stack
		lua_pushvalue(L, -1);
		lua_setfield(L, -3, TableName.c_str());
	}

	// Remove the Metatable table from the stack
	lua_remove(L, -2);

	return true;
}

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

bool LuaBindhelper::_CreateTable(lua_State *L, const Common::String &TableName) {
	const char *PartBegin = TableName.c_str();

	while (PartBegin - TableName.c_str() < (int)TableName.size()) {
		const char *PartEnd = strchr(PartBegin, '.');
		if (!PartEnd)
			PartEnd = PartBegin + strlen(PartBegin);
		Common::String SubTableName(PartBegin, PartEnd);

		// Tables with an empty string as the name are not allowed
		if (SubTableName.size() == 0)
			return false;

		// Verify that the table with the name already exists
		// The first round will be searched in the global namespace, with later passages
		// in the corresponding parent table in the stack
		if (PartBegin == TableName.c_str()) {
			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);
		}

		// If it doesn't exist, create table
		if (lua_isnil(L, -1)) {
			// Pop nil from stack
			lua_pop(L, 1);

			// Create new table
			lua_newtable(L);
			lua_pushstring(L, SubTableName.c_str());
			lua_pushvalue(L, -2);
			if (PartBegin == TableName.c_str())
				lua_settable(L, LUA_GLOBALSINDEX);
			else {
				lua_settable(L, -4);
				lua_remove(L, -2);
			}
		}

		PartBegin = PartEnd + 1;
	}

	return true;
}

} // End of namespace Sword25

namespace {
Common::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;
	}

	Common::String Result(lua_tostring(L, -1));
	lua_pop(L, 1);

	return Result;
}
}

namespace Sword25 {

Common::String LuaBindhelper::StackDump(lua_State *L) {
	Common::String 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;
}

Common::String LuaBindhelper::TableDump(lua_State *L) {
	Common::String oss;

	oss += "------------------- Table Dump -------------------\n";

	lua_pushnil(L);
	while (lua_next(L, -2) != 0) {
		// Get the value of the current element on top of the stack, including the index
		oss += GetLuaValueInfo(L, -2) + " : " + GetLuaValueInfo(L, -1) + "\n";

		// Pop value from the stack. The index is then ready for the next call to lua_next()
		lua_pop(L, 1);
	}

	oss += "-------------- Table Dump Finished ---------------\n";

	return oss;
}

} // End of namespace Sword25