forked from Jo-Tran/cryingdamson-0.3.6-8.60-V8.2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luascript.cpp
10073 lines (8416 loc) · 248 KB
/
luascript.cpp
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
////////////////////////////////////////////////////////////////////////
// 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 3 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, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////
#include "otpch.h"
#include "luascript.h"
#include "scriptmanager.h"
#include <boost/filesystem.hpp>
#include <boost/any.hpp>
#include <iostream>
#include <iomanip>
#include "player.h"
#include "item.h"
#include "teleport.h"
#include "town.h"
#include "house.h"
#include "housetile.h"
#include "database.h"
#include "iologindata.h"
#include "ioban.h"
#include "iomapserialize.h"
#include "talkaction.h"
#include "spells.h"
#include "combat.h"
#include "condition.h"
#include "baseevents.h"
#include "monsters.h"
#include "raids.h"
#include "configmanager.h"
#include "vocation.h"
#include "status.h"
#include "game.h"
#include "chat.h"
extern Game g_game;
extern Monsters g_monsters;
extern Chat g_chat;
extern ConfigManager g_config;
extern Spells* g_spells;
extern TalkActions* g_talkActions;
enum
{
EVENT_ID_LOADING = 1,
EVENT_ID_USER = 1000,
};
ScriptEnviroment::AreaMap ScriptEnviroment::m_areaMap;
uint32_t ScriptEnviroment::m_lastAreaId = 0;
ScriptEnviroment::CombatMap ScriptEnviroment::m_combatMap;
uint32_t ScriptEnviroment::m_lastCombatId = 0;
ScriptEnviroment::ConditionMap ScriptEnviroment::m_conditionMap;
uint32_t ScriptEnviroment::m_lastConditionId = 0;
ScriptEnviroment::ThingMap ScriptEnviroment::m_globalMap;
ScriptEnviroment::StorageMap ScriptEnviroment::m_storageMap;
ScriptEnviroment::TempItemListMap ScriptEnviroment::m_tempItems;
ScriptEnviroment::ScriptEnviroment()
{
m_lastUID = 70000;
m_loaded = true;
reset();
}
ScriptEnviroment::~ScriptEnviroment()
{
for(CombatMap::iterator it = m_combatMap.begin(); it != m_combatMap.end(); ++it)
delete it->second;
m_combatMap.clear();
for(AreaMap::iterator it = m_areaMap.begin(); it != m_areaMap.end(); ++it)
delete it->second;
m_areaMap.clear();
reset();
}
void ScriptEnviroment::reset()
{
m_scriptId = m_callbackId = 0;
m_timerEvent = false;
m_realPos = Position();
m_interface = NULL;
for(TempItemListMap::iterator mit = m_tempItems.begin(); mit != m_tempItems.end(); ++mit)
{
ItemList itemList = mit->second;
for(ItemList::iterator it = itemList.begin(); it != itemList.end(); ++it)
{
if((*it)->getParent() == VirtualCylinder::virtualCylinder)
g_game.freeThing(*it);
}
}
m_tempItems.clear();
for(DBResultMap::iterator it = m_tempResults.begin(); it != m_tempResults.end(); ++it)
{
if(it->second)
it->second->free();
}
m_tempResults.clear();
m_localMap.clear();
}
bool ScriptEnviroment::saveGameState()
{
if(!g_config.getBool(ConfigManager::SAVE_GLOBAL_STORAGE))
return true;
Database* db = Database::getInstance();
DBQuery query;
query << "DELETE FROM `global_storage` WHERE `world_id` = " << g_config.getNumber(ConfigManager::WORLD_ID) << ";";
if(!db->executeQuery(query.str()))
return false;
DBInsert query_insert(db);
query_insert.setQuery("INSERT INTO `global_storage` (`key`, `world_id`, `value`) VALUES ");
for(StorageMap::const_iterator it = m_storageMap.begin(); it != m_storageMap.end(); ++it)
{
char buffer[25 + it->second.length()];
sprintf(buffer, "%u, %u, %s", it->first, g_config.getNumber(ConfigManager::WORLD_ID), db->escapeString(it->second).c_str());
if(!query_insert.addRow(buffer))
return false;
}
return query_insert.execute();
}
bool ScriptEnviroment::loadGameState()
{
Database* db = Database::getInstance();
DBResult* result;
DBQuery query;
query << "SELECT `key`, `value` FROM `global_storage` WHERE `world_id` = " << g_config.getNumber(ConfigManager::WORLD_ID) << ";";
if((result = db->storeQuery(query.str())))
{
do
m_storageMap[result->getDataInt("key")] = result->getDataString("value");
while(result->next());
result->free();
}
query.str("");
return true;
}
bool ScriptEnviroment::setCallbackId(int32_t callbackId, LuaScriptInterface* interface)
{
if(!m_callbackId)
{
m_callbackId = callbackId;
m_interface = interface;
return true;
}
//nested callbacks are not allowed
if(m_interface)
m_interface->errorEx("Nested callbacks!");
return false;
}
void ScriptEnviroment::getInfo(int32_t& scriptId, std::string& desc, LuaScriptInterface*& interface, int32_t& callbackId, bool& timerEvent)
{
scriptId = m_scriptId;
desc = m_eventdesc;
interface = m_interface;
callbackId = m_callbackId;
timerEvent = m_timerEvent;
}
void ScriptEnviroment::addUniqueThing(Thing* thing)
{
Item* item = thing->getItem();
if(!item || !item->getUniqueId())
return;
if(m_globalMap[item->getUniqueId()])
{
if(item->getActionId() != 2000) //scripted quest system
std::cout << "Duplicate uniqueId " << item->getUniqueId() << std::endl;
}
else
m_globalMap[item->getUniqueId()] = thing;
}
void ScriptEnviroment::removeUniqueThing(Thing* thing)
{
Item* item = thing->getItem();
if(!item || !item->getUniqueId())
return;
ThingMap::iterator it = m_globalMap.find(item->getUniqueId());
if(it != m_globalMap.end())
m_globalMap.erase(it);
}
uint32_t ScriptEnviroment::addThing(Thing* thing)
{
if(!thing || thing->isRemoved())
return 0;
for(ThingMap::iterator it = m_localMap.begin(); it != m_localMap.end(); ++it)
{
if(it->second == thing)
return it->first;
}
if(Creature* creature = thing->getCreature())
{
m_localMap[creature->getID()] = thing;
return creature->getID();
}
if(Item* item = thing->getItem())
{
uint32_t tmp = item->getUniqueId();
if(tmp)
{
m_localMap[tmp] = thing;
return tmp;
}
}
while(m_localMap.find(m_lastUID) != m_localMap.end())
++m_lastUID;
m_localMap[m_lastUID] = thing;
return m_lastUID;
}
void ScriptEnviroment::insertThing(uint32_t uid, Thing* thing)
{
if(!m_localMap[uid])
m_localMap[uid] = thing;
else
std::cout << "[Error - ScriptEnviroment::insertThing] Thing uid already taken" << std::endl;
}
Thing* ScriptEnviroment::getThingByUID(uint32_t uid)
{
Thing* tmp = m_localMap[uid];
if(tmp && !tmp->isRemoved())
return tmp;
tmp = m_globalMap[uid];
if(tmp && !tmp->isRemoved())
return tmp;
if(uid >= 0x10000000)
{
tmp = g_game.getCreatureByID(uid);
if(tmp && !tmp->isRemoved())
{
m_localMap[uid] = tmp;
return tmp;
}
}
return NULL;
}
Item* ScriptEnviroment::getItemByUID(uint32_t uid)
{
if(Thing* tmp = getThingByUID(uid))
{
if(Item* item = tmp->getItem())
return item;
}
return NULL;
}
Container* ScriptEnviroment::getContainerByUID(uint32_t uid)
{
if(Item* tmp = getItemByUID(uid))
{
if(Container* container = tmp->getContainer())
return container;
}
return NULL;
}
Creature* ScriptEnviroment::getCreatureByUID(uint32_t uid)
{
if(Thing* tmp = getThingByUID(uid))
{
if(Creature* creature = tmp->getCreature())
return creature;
}
return NULL;
}
Player* ScriptEnviroment::getPlayerByUID(uint32_t uid)
{
if(Thing* tmp = getThingByUID(uid))
{
if(Creature* creature = tmp->getCreature())
{
if(Player* player = creature->getPlayer())
return player;
}
}
return NULL;
}
void ScriptEnviroment::removeThing(uint32_t uid)
{
ThingMap::iterator it;
it = m_localMap.find(uid);
if(it != m_localMap.end())
m_localMap.erase(it);
it = m_globalMap.find(uid);
if(it != m_globalMap.end())
m_globalMap.erase(it);
}
uint32_t ScriptEnviroment::addCombatArea(CombatArea* area)
{
uint32_t newAreaId = m_lastAreaId + 1;
m_areaMap[newAreaId] = area;
m_lastAreaId++;
return newAreaId;
}
CombatArea* ScriptEnviroment::getCombatArea(uint32_t areaId)
{
AreaMap::const_iterator it = m_areaMap.find(areaId);
if(it != m_areaMap.end())
return it->second;
return NULL;
}
uint32_t ScriptEnviroment::addCombatObject(Combat* combat)
{
uint32_t newCombatId = m_lastCombatId + 1;
m_combatMap[newCombatId] = combat;
m_lastCombatId++;
return newCombatId;
}
Combat* ScriptEnviroment::getCombatObject(uint32_t combatId)
{
CombatMap::iterator it = m_combatMap.find(combatId);
if(it != m_combatMap.end())
return it->second;
return NULL;
}
uint32_t ScriptEnviroment::addConditionObject(Condition* condition)
{
uint32_t newConditionId = m_lastConditionId + 1;
m_conditionMap[newConditionId] = condition;
m_lastConditionId++;
return m_lastConditionId;
}
Condition* ScriptEnviroment::getConditionObject(uint32_t conditionId)
{
ConditionMap::iterator it = m_conditionMap.find(conditionId);
if(it != m_conditionMap.end())
return it->second;
return NULL;
}
void ScriptEnviroment::addTempItem(ScriptEnviroment* env, Item* item)
{
m_tempItems[env].push_back(item);
}
void ScriptEnviroment::removeTempItem(ScriptEnviroment* env, Item* item)
{
ItemList itemList = m_tempItems[env];
ItemList::iterator it = std::find(itemList.begin(), itemList.end(), item);
if(it != itemList.end())
itemList.erase(it);
}
void ScriptEnviroment::removeTempItem(Item* item)
{
for(TempItemListMap::iterator mit = m_tempItems.begin(); mit != m_tempItems.end(); ++mit)
{
ItemList itemList = mit->second;
ItemList::iterator it = std::find(itemList.begin(), itemList.end(), item);
if(it != itemList.end())
itemList.erase(it);
}
}
uint32_t ScriptEnviroment::addResult(DBResult* res)
{
uint32_t lastId = 0;
while(m_tempResults.find(lastId) != m_tempResults.end())
lastId++;
m_tempResults[lastId] = res;
return lastId;
}
bool ScriptEnviroment::removeResult(uint32_t id)
{
DBResultMap::iterator it = m_tempResults.find(id);
if(it == m_tempResults.end())
return false;
if(it->second)
it->second->free();
m_tempResults.erase(it);
return true;
}
DBResult* ScriptEnviroment::getResultByID(uint32_t id)
{
DBResultMap::iterator it = m_tempResults.find(id);
if(it != m_tempResults.end())
return it->second;
return NULL;
}
bool ScriptEnviroment::getStorage(const uint32_t key, std::string& value) const
{
StorageMap::const_iterator it = m_storageMap.find(key);
if(it != m_storageMap.end())
{
value = it->second;
return true;
}
value = "-1";
return false;
}
void ScriptEnviroment::streamVariant(std::stringstream& stream, const std::string& local, const LuaVariant& var)
{
if(!local.empty())
stream << "local " << local << " = {" << std::endl;
stream << "type = " << var.type;
switch(var.type)
{
case VARIANT_NUMBER:
stream << "," << std::endl << "number = " << var.number;
break;
case VARIANT_STRING:
stream << "," << std::endl << "string = \"" << var.text << "\"";
break;
case VARIANT_TARGETPOSITION:
case VARIANT_POSITION:
{
stream << "," << std::endl;
streamPosition(stream, "pos", var.pos);
break;
}
case VARIANT_NONE:
default:
break;
}
if(!local.empty())
stream << std::endl << "}" << std::endl;
}
void ScriptEnviroment::streamThing(std::stringstream& stream, const std::string& local, Thing* thing, uint32_t id/* = 0*/)
{
if(!local.empty())
stream << "local " << local << " = {" << std::endl;
if(thing && thing->getItem())
{
const Item* item = thing->getItem();
if(!id)
id = addThing(thing);
stream << "uid = " << id << "," << std::endl;
stream << "itemid = " << item->getID() << "," << std::endl;
if(item->hasSubType())
stream << "type = " << item->getSubType() << "," << std::endl;
else
stream << "type = 0," << std::endl;
stream << "actionid = " << item->getActionId() << std::endl;
}
else if(thing && thing->getCreature())
{
const Creature* creature = thing->getCreature();
if(!id)
id = creature->getID();
stream << "uid = " << id << "," << std::endl;
stream << "itemid = 1," << std::endl;
if(creature->getPlayer())
stream << "type = 1," << std::endl;
else if(creature->getMonster())
stream << "type = 2," << std::endl;
else
stream << "type = 3," << std::endl;
if(const Player* player = creature->getPlayer())
stream << "actionid = " << player->getGUID() << "," << std::endl;
else
stream << "actionid = 0" << std::endl;
}
else
{
stream << "uid = 0," << std::endl;
stream << "itemid = 0," << std::endl;
stream << "type = 0," << std::endl;
stream << "actionid = 0" << std::endl;
}
if(!local.empty())
stream << "}" << std::endl;
}
void ScriptEnviroment::streamPosition(std::stringstream& stream, const std::string& local, const Position& position, uint32_t stackpos)
{
if(!local.empty())
stream << "local " << local << " = {" << std::endl;
stream << "x = " << position.x << "," << std::endl;
stream << "y = " << position.y << "," << std::endl;
stream << "z = " << position.z << "," << std::endl;
stream << "stackpos = " << stackpos << std::endl;
if(!local.empty())
stream << "}" << std::endl;
}
void ScriptEnviroment::streamOutfit(std::stringstream& stream, const std::string& local, const Outfit_t& outfit)
{
if(!local.empty())
stream << "local " << local << " = {" << std::endl;
stream << "lookType = " << outfit.lookType << "," << std::endl;
stream << "lookTypeEx = " << outfit.lookTypeEx << "," << std::endl;
stream << "lookHead = " << outfit.lookHead << "," << std::endl;
stream << "lookBody = " << outfit.lookBody << "," << std::endl;
stream << "lookLegs = " << outfit.lookLegs << "," << std::endl;
stream << "lookFeet = " << outfit.lookFeet << "," << std::endl;
stream << "lookAddons = " << outfit.lookAddons << std::endl;
if(!local.empty())
stream << "}" << std::endl;
}
std::string LuaScriptInterface::getError(ErrorCode_t code)
{
switch(code)
{
case LUA_ERROR_PLAYER_NOT_FOUND:
return "Player not found";
case LUA_ERROR_MONSTER_NOT_FOUND:
return "Monster not found";
case LUA_ERROR_NPC_NOT_FOUND:
return "NPC not found";
case LUA_ERROR_CREATURE_NOT_FOUND:
return "Creature not found";
case LUA_ERROR_ITEM_NOT_FOUND:
return "Item not found";
case LUA_ERROR_THING_NOT_FOUND:
return "Thing not found";
case LUA_ERROR_TILE_NOT_FOUND:
return "Tile not found";
case LUA_ERROR_HOUSE_NOT_FOUND:
return "House not found";
case LUA_ERROR_COMBAT_NOT_FOUND:
return "Combat not found";
case LUA_ERROR_CONDITION_NOT_FOUND:
return "Condition not found";
case LUA_ERROR_AREA_NOT_FOUND:
return "Area not found";
case LUA_ERROR_CONTAINER_NOT_FOUND:
return "Container not found";
case LUA_ERROR_VARIANT_NOT_FOUND:
return "Variant not found";
case LUA_ERROR_VARIANT_UNKNOWN:
return "Unknown variant type";
case LUA_ERROR_SPELL_NOT_FOUND:
return "Spell not found";
default:
break;
}
return "Invalid error code!";
}
ScriptEnviroment LuaScriptInterface::m_scriptEnv[21];
int32_t LuaScriptInterface::m_scriptEnvIndex = -1;
LuaScriptInterface::LuaScriptInterface(std::string interfaceName)
{
m_luaState = NULL;
m_interfaceName = interfaceName;
m_lastEventTimerId = 1000;
}
LuaScriptInterface::~LuaScriptInterface()
{
closeState();
}
bool LuaScriptInterface::reInitState()
{
closeState();
return initState();
}
bool LuaScriptInterface::loadBuffer(const std::string& text, Npc* npc/* = NULL*/)
{
//loads buffer as a chunk at stack top
int32_t ret = luaL_loadbuffer(m_luaState, text.c_str(), text.length(), "loadBuffer");
if(ret)
{
m_lastError = popString(m_luaState);
error(NULL, m_lastError);
return false;
}
//check that it is loaded as a function
if(!lua_isfunction(m_luaState, -1))
return false;
m_loadingFile = "buffer";
reserveEnv();
ScriptEnviroment* env = getEnv();
env->setScriptId(EVENT_ID_LOADING, this);
env->setNpc(npc);
//execute it
ret = lua_pcall(m_luaState, 0, 0, 0);
if(ret)
{
error(NULL, popString(m_luaState));
releaseEnv();
return false;
}
releaseEnv();
return true;
}
bool LuaScriptInterface::loadFile(const std::string& file, Npc* npc/* = NULL*/)
{
//loads file as a chunk at stack top
int32_t ret = luaL_loadfile(m_luaState, file.c_str());
if(ret)
{
m_lastError = popString(m_luaState);
std::cout << "[Error - LuaScriptInterface::loadFile] " << m_lastError << std::endl;
return false;
}
//check that it is loaded as a function
if(!lua_isfunction(m_luaState, -1))
return false;
m_loadingFile = file;
reserveEnv();
ScriptEnviroment* env = getEnv();
env->setScriptId(EVENT_ID_LOADING, this);
env->setNpc(npc);
//execute it
ret = lua_pcall(m_luaState, 0, 0, 0);
if(ret)
{
error(NULL, popString(m_luaState));
releaseEnv();
return false;
}
releaseEnv();
return true;
}
bool LuaScriptInterface::loadDirectory(const std::string& dir, Npc* npc/* = NULL*/)
{
StringVec files;
for(boost::filesystem::directory_iterator it(dir), end; it != end; ++it)
{
std::string s = it->leaf();
if(!boost::filesystem::is_directory(it->status()) && (s.size() > 4 ? s.substr(s.size() - 4) : "") == ".lua")
files.push_back(s);
}
std::sort(files.begin(), files.end());
for(StringVec::iterator it = files.begin(); it != files.end(); ++it)
{
if(!loadFile(dir + (*it), npc))
return false;
}
return true;
}
int32_t LuaScriptInterface::getEvent(const std::string& eventName)
{
//get our events table
lua_getfield(m_luaState, LUA_REGISTRYINDEX, "EVENTS");
if(!lua_istable(m_luaState, -1))
{
lua_pop(m_luaState, 1);
return -1;
}
//get current event function pointer
lua_getglobal(m_luaState, eventName.c_str());
if(!lua_isfunction(m_luaState, -1))
{
lua_pop(m_luaState, 1);
return -1;
}
//save in our events table
lua_pushnumber(m_luaState, m_runningEventId);
lua_pushvalue(m_luaState, -2);
lua_rawset(m_luaState, -4);
lua_pop(m_luaState, 2);
//reset global value of this event
lua_pushnil(m_luaState);
lua_setglobal(m_luaState, eventName.c_str());
m_cacheFiles[m_runningEventId] = m_loadingFile + ":" + eventName;
++m_runningEventId;
return m_runningEventId - 1;
}
std::string LuaScriptInterface::getScript(int32_t scriptId)
{
const static std::string tmp = "(Unknown script file)";
if(scriptId != EVENT_ID_LOADING)
{
ScriptsCache::iterator it = m_cacheFiles.find(scriptId);
if(it != m_cacheFiles.end())
return it->second;
return tmp;
}
return m_loadingFile;
}
void LuaScriptInterface::error(const char* function, const std::string& desc)
{
int32_t script, callback;
bool timer;
std::string event;
LuaScriptInterface* interface;
getEnv()->getInfo(script, event, interface, callback, timer);
if(interface)
{
std::cout << std::endl << "[Error - " << interface->getName() << "] " << std::endl;
if(callback)
std::cout << "In a callback: " << interface->getScript(callback) << std::endl;
if(timer)
std::cout << (callback ? "from" : "In") << " a timer event called from: " << std::endl;
std::cout << interface->getScript(script) << std::endl << "Description: ";
}
else
std::cout << std::endl << "[Lua Error] ";
std::cout << event << std::endl;
if(function)
std::cout << "(" << function << ") ";
std::cout << desc << std::endl;
}
bool LuaScriptInterface::pushFunction(int32_t function)
{
lua_getfield(m_luaState, LUA_REGISTRYINDEX, "EVENTS");
if(lua_istable(m_luaState, -1))
{
lua_pushnumber(m_luaState, function);
lua_rawget(m_luaState, -2);
lua_remove(m_luaState, -2);
if(lua_isfunction(m_luaState, -1))
return true;
}
return false;
}
bool LuaScriptInterface::initState()
{
m_luaState = luaL_newstate();
if(!m_luaState)
return false;
luaL_openlibs(m_luaState);
registerFunctions();
if(!loadDirectory(getFilePath(FILE_TYPE_OTHER, "lib/"), NULL))
std::cout << "[Warning - LuaScriptInterface::initState] Cannot load " << getFilePath(FILE_TYPE_OTHER, "lib/") << std::endl;
lua_newtable(m_luaState);
lua_setfield(m_luaState, LUA_REGISTRYINDEX, "EVENTS");
m_runningEventId = EVENT_ID_USER;
return true;
}
bool LuaScriptInterface::closeState()
{
if(!m_luaState)
return false;
m_cacheFiles.clear();
for(LuaTimerEvents::iterator it = m_timerEvents.begin(); it != m_timerEvents.end(); ++it)
{
for(std::list<int32_t>::iterator lt = it->second.parameters.begin(); lt != it->second.parameters.end(); ++lt)
luaL_unref(m_luaState, LUA_REGISTRYINDEX, *lt);
it->second.parameters.clear();
luaL_unref(m_luaState, LUA_REGISTRYINDEX, it->second.function);
}
m_timerEvents.clear();
lua_close(m_luaState);
return true;
}
void LuaScriptInterface::executeTimer(uint32_t eventIndex)
{
LuaTimerEvents::iterator it = m_timerEvents.find(eventIndex);
if(it != m_timerEvents.end())
{
//push function
lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, it->second.function);
//push parameters
for(std::list<int32_t>::reverse_iterator rt = it->second.parameters.rbegin(); rt != it->second.parameters.rend(); ++rt)
lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, *rt);
//call the function
if(reserveEnv())
{
ScriptEnviroment* env = getEnv();
env->setTimerEvent();
env->setScriptId(it->second.scriptId, this);
callFunction(it->second.parameters.size());
releaseEnv();
}
else
std::cout << "[Error] Call stack overflow. LuaScriptInterface::executeTimer" << std::endl;
//free resources
for(std::list<int32_t>::iterator lt = it->second.parameters.begin(); lt != it->second.parameters.end(); ++lt)
luaL_unref(m_luaState, LUA_REGISTRYINDEX, *lt);
it->second.parameters.clear();
luaL_unref(m_luaState, LUA_REGISTRYINDEX, it->second.function);
m_timerEvents.erase(it);
}
}
int32_t LuaScriptInterface::handleFunction(lua_State* L)
{
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
if(!lua_istable(L, -1))
{
lua_pop(L, 1);
return 1;
}
lua_getfield(L, -1, "traceback");
if(!lua_isfunction(L, -1))
{
lua_pop(L, 2);
return 1;
}
lua_pushvalue(L, 1);
lua_pushinteger(L, 2);
lua_call(L, 2, 1);
return 1;
}
bool LuaScriptInterface::callFunction(uint32_t params)
{
int32_t size = lua_gettop(m_luaState), handler = lua_gettop(m_luaState) - params;
lua_pushcfunction(m_luaState, handleFunction);
bool result = false;
lua_insert(m_luaState, handler);
if(lua_pcall(m_luaState, params, 1, handler))
LuaScriptInterface::error(NULL, LuaScriptInterface::popString(m_luaState));
else
result = (int32_t)LuaScriptInterface::popBoolean(m_luaState);
lua_remove(m_luaState, handler);
if((lua_gettop(m_luaState) + (int32_t)params + 1) != size)
LuaScriptInterface::error(NULL, "Stack size changed!");
return result;
}
void LuaScriptInterface::dumpStack(lua_State* L/* = NULL*/)
{
if(!L)
L = m_luaState;
int32_t stack = lua_gettop(L);
if(!stack)
return;
std::cout << "Stack size: " << stack << std::endl;
for(int32_t i = 1; i <= stack ; ++i)
std::cout << lua_typename(m_luaState, lua_type(m_luaState, -i)) << " " << lua_topointer(m_luaState, -i) << std::endl;
}
void LuaScriptInterface::pushVariant(lua_State* L, const LuaVariant& var)
{
lua_newtable(L);
setField(L, "type", var.type);
switch(var.type)
{
case VARIANT_NUMBER:
setField(L, "number", var.number);
break;
case VARIANT_STRING:
setField(L, "string", var.text);
break;
case VARIANT_TARGETPOSITION:
case VARIANT_POSITION:
{
lua_pushstring(L, "pos");
pushPosition(L, var.pos);
pushTable(L);
break;
}
case VARIANT_NONE:
break;
}
}
void LuaScriptInterface::pushThing(lua_State* L, Thing* thing, uint32_t id/* = 0*/)
{
lua_newtable(L);
if(thing && thing->getItem())
{
const Item* item = thing->getItem();
if(!id)
id = getEnv()->addThing(thing);
setField(L, "uid", id);
setField(L, "itemid", item->getID());
if(item->hasSubType())
setField(L, "type", item->getSubType());
else
setField(L, "type", 0);
setField(L, "actionid", item->getActionId());
}
else if(thing && thing->getCreature())