Advertisement
Guest User

test.cpp

a guest
Jul 1st, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. //  g++ -std=c++11 test.cpp `pkg-config --cflags lua51`  `pkg-config --libs lua51`  -o ver-lua    && ./ver-lua
  2. //  g++ -std=c++11 test.cpp `pkg-config --cflags luajit` `pkg-config --libs luajit` -o ver-luajit && ./ver-luajit
  3.  
  4. #include    <iostream>
  5. #include    <sstream>
  6. #include    <string>
  7.  
  8. #include    <lua.hpp>
  9.  
  10. #define     PRINT_LUA_VERSION \
  11. "if not jit then" \
  12. "   print(_VERSION) " \
  13. "else" \
  14. "   print(jit.version) " \
  15. "end"
  16.  
  17. inline float mystof(const std::string &str) {
  18.     return atof(str.c_str());
  19. }
  20. #define stof mystof
  21.  
  22. inline std::string ftos(float f) {
  23.     std::ostringstream oss;
  24.     oss << f;
  25.     return oss.str();
  26. }
  27.  
  28. int my_func(lua_State* L)
  29. {
  30.     float x = (float)lua_tonumber(L, 1);
  31.     std::string str = ftos(x);
  32.     std::cout << "1st param(string):" << str << std::endl;
  33.  
  34.     lua_settop(L, 0);
  35.     //lua_pushnumber(L, stod(str));     // double
  36.     lua_pushnumber(L, stof(str));       // float
  37.     return 1;
  38. }
  39.  
  40. int main() {
  41.     lua_State* L = luaL_newstate();
  42.     luaL_openlibs(L);
  43.     lua_register(L, "my_func", my_func);
  44.  
  45.     if (luaL_dostring(L, PRINT_LUA_VERSION)) {
  46.         lua_close(L);
  47.         exit(EXIT_FAILURE);
  48.     }
  49.  
  50.     if (luaL_dostring(L, "print('function result  :' .. my_func(0.1))")) {
  51.         lua_close(L);
  52.         exit(EXIT_FAILURE);
  53.     }
  54.     lua_close(L);
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement