lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello dear lua community,

I'm experimenting with baby C-server with lua scripting on it. I have
met the following issue: if I load the sample script from my server 
luaL_loadstring tells about syntax error; meanwhile when I run 
my script in console it compiles (and runs) without any problems.

$ lua ./script.lua && echo "OK"
ls      -lah    /       function: 0x7e2c00
OK

$ cat script.lua 
local my_callback = function(exit_code, stdout, stderr)
   print 'Hello from callback';
end

my_fun = print;
--print 'Hello from lua';
my_fun(
   'ls',
   '-lah',
   '/',
   my_callback);
--print 'Goodbye from lua';

$ cat my.c 
#include <fcntl.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int lua_my_fun(lua_State *L) {
  return 0;
}

static char* script;

static int load_script(char* script_path) {
  struct stat script_stat;
  int result;
  FILE *script_file;
  size_t records_read;

  result = stat(script_path, &script_stat);
  if (result) {
    perror("error get script stats");
    return -1;
  }

  script = malloc(script_stat.st_size);
  if (!script) {
    fprintf(stderr, "cannot allocate %ld bytes for script\n", script_stat.st_size);
    return -1;
  }

  script_file = fopen(script_path, "r");
  if (!script_file) {
    perror("cannot open script file");
    return -1;
  }

  records_read = fread(script, script_stat.st_size, 1, script_file);
  if (records_read != 1) {
    fprintf(stderr, "error reading script %s\n", script_path);
    return -1;
  }

  /* success */
  return 0;
}

int main() {
  load_script("script.lua");
  lua_State *L = luaL_newstate();
  luaL_openlibs(L);
  lua_pushcfunction(L, lua_my_fun);
  lua_setglobal(L, "my_fun");
  if (luaL_loadstring(L, script)) {
    fprintf(stderr, "error in script:\n %s\n:%s\n", script, lua_tostring(L, -1));
  }
}

$ cc my.c -o a -l lua && ./a                                                                                                  
error in script:
 local my_callback = function(exit_code, stdout, stderr)
   print 'Hello from callback';
end

my_fun = print;
--print 'Hello from lua';
my_fun(
   'ls',
   '-lah',
   '/',
   my_callback);
--print 'Goodbye from lua';
A
:[string "local my_callback = function(exit_code, stdout, stderr)..."]:13: '=' expected near 'char(2)'

In the same time, when I delete comments in script.lua, it executes
correctly. What is wrong? 

Thanks for any help!

PS. 
$ lua -v
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio


-- 
Best regards,
Bασιλίσκος Arcticus ὑπέρnihilisticus 
(aka Ivan Baidakou) <basiliscos@openmailbox.org>