eliasdaler

Lua tutorial part 3. paste 1.

Dec 1st, 2013
2,500
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extern "C" {
  2. # include "lua.h"
  3. # include "lauxlib.h"
  4. # include "lualib.h"
  5. }
  6.  
  7. #include <iostream>
  8. #include <string>
  9. #include "luawrapper.hpp"
  10.  
  11. class Character {
  12. public:
  13.     Character(const char* name, int hp);
  14.     void say(const char* text);
  15.     void heal(Character* character);
  16.         const char* getName() { return name;}
  17.     int getHealth() { return health; }
  18.     void setHealth(int hp) { health = hp; }
  19. private:
  20.     const char* name;
  21.     int health;
  22. };
  23.  
  24. Character::Character(const char* name, int hp) {
  25.     this->name = name;
  26.     health = hp;
  27. }
  28.  
  29. void Character::say(const char* text) {
  30.     std::cout<<name<<":"<<text<<std::endl;
  31. }
  32.  
  33. void Character::heal(Character* character) {
  34.     character->setHealth(100);
  35. }
  36.  
  37. Character* Character_new(lua_State* L) {
  38.     const char* name = luaL_checkstring(L, 1);
  39.     int hp = luaL_checknumber(L, 2);
  40.     return new Character(name, hp);
  41. }
  42.  
  43. int Character_getName(lua_State* L) {
  44.     Character* character = luaW_check<Character>(L, 1);
  45.     lua_pushstring(L, character->getName());
  46.     return 1;
  47. }
  48.  
  49.  
  50. int Character_getHealth(lua_State* L) {
  51.     Character* character = luaW_check<Character>(L, 1);
  52.     lua_pushnumber(L, character->getHealth());
  53.     return 1;
  54. }
  55.  
  56. int Character_setHealth(lua_State* L) {
  57.     Character* character = luaW_check<Character>(L, 1);
  58.     int hp = luaL_checknumber(L, 2);
  59.     character->setHealth(hp);
  60.     return 0;
  61. }
  62.  
  63.  
  64. static luaL_Reg Character_table[] = {
  65.     { NULL, NULL }
  66. };
  67.  
  68. static luaL_Reg Character_metatable[] = {
  69.     { "getName", Character_getName },
  70.     { "getHealth", Character_getHealth },
  71.     { "setHealth", Character_setHealth },
  72.     { NULL, NULL }
  73. };
  74.  
  75. static int luaopen_Character(lua_State* L) {
  76.     luaW_register<Character>(L, "Character", Character_table, Character_metatable, Character_new);
  77.     return 1;
  78. }
  79.  
  80. int main() {
  81.     lua_State* L = luaL_newstate();  
  82.     luaL_openlibs(L);
  83.     luaopen_Character(L);
  84.     if (luaL_loadfile(L, "test.lua")) {
  85.         std::cout<<"Error, can't open script"<<std::endl;
  86.     }
  87.    
  88.     lua_pcall(L, 0, 0, 0);
  89. }
RAW Paste Data