2016年11月11日 星期五

Node.js calling Lua under in Windows 10




1.      Use node-gyp
npm install -g node-gyp

2.      Build with vc++ compiler
I.            First, install python 2.7.
II.          Install Visual studio 2015 community.
III.        In node.js promot type:
npm config set python python2.7
npm config set msvs_version 2015

Note: I couldn’t build successfully with VC++ build tools 2015; the error was the version of compiler is wrong. I solved this problem after install VS2005 community.

3.      New a file “binding.gyp” in your working folder. The content is

<pre class="prettyprint">
{
  "targets": [
    {
      "target_name": "binding", ## the name you want
      "sources": [ "src/binding.cc" ], ## the cpp source code path
      'include_dirs': ['include'],
      'libraries': ['lib/lua53.lib' ]
    }
  ]
}
</pre>
4.      Generate binding.cc which calls lua C API
<code class="prettyprint">
#include <node.h>
#include "lua.hpp"

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

lua_State *L ;

 int luaadd ( int x, int y )
 {
     int sum;  
     lua_getglobal(L, "add");      
     lua_pushnumber(L, x);   
     lua_pushnumber(L, y);
     lua_call(L, 2, 1);
     sum = (int)lua_tonumber(L, -1);
     lua_pop(L, 1);
         return sum;
 }

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  L = luaL_newstate();
        luaL_openlibs(L);
  /* Load the file containing the script we are going to run */
  int status = luaL_dofile(L, "add.lua");
  if (status) {
  /* If something went wrong, error message is at the top of the stack */
      fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
      exit(1);
 }  
   
 int sum = luaadd( 10, 11);
  //String::NewFromUtf8(isolate, "C addon working:");
  args.GetReturnValue().Set(sum);
  lua_close(L);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(addon, init)
}
</code>
Note: include lua.hpp when using C++ compiler.

5.      Create add.lua in the working folder
function add(x,y)
return x+y
end
6.      Create hello.js in the woring folder
// hello.js
const addon = require('./build/Release/binding.node');##your target name in binding.gyp .node
console.log(addon.hello());Command: node-gyp configure ## your export method name in cpp

7.      Place the lua.lib in the “/build” folder in your working folder. Don’t have to place lua.exe or lua.dll.
8.      Command: node-gyp configure
9.      Command: node-gyp build
10.  Node.js cmd: Node hello.js
You can see the result from lua