lua-users home
lua-l archive

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

Your Lua code is invalid, and so luaL_loadstring() will fail. This will leave an empty stack and the following lua_pcall() will thus fail. As Rena notes, the stack is not checked in the default build for performance reasons (hence the crash), if you enable this you will see the error. To enable checking, use “-DLUA_USE_APICHECK” when building.

The Lua code is wrong in the first line, where you both attempt to create a function by name (“modify_content_length” and also assign it to the variable “c_function". You should do one or the other, but not both:

c_function = function(msg, length) …
function modify_content_length(msg, length)

As other posters have noted, you should also push the arguments in left to right order (so msg gets pushed first, not length). Also, it’s not good design to pass the length of the string to the Lua function (as others noted), use Lua’s # operator instead.


On Jun 27, 2014, at 9:17 AM, Austin Einter <> wrote:

Hi All
I have a small c code, it is crashing when invoking lua_call.
Corresponding lua script (without c code works fine)
When same thing trying to from a C code with Lua embedded getting crash.

Please somebody help why it is crasing..

Code as below.

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <lua5.2/lua.h>
#include <lua5.2/lualib.h>
#include <lua5.2/lualib.h>

const char *c_function = "function modify_content_length(msg, length) "
                         "local offset = string.find(msg, '\r\n\r\n\', 1, true) "
                         "if(offset == nil) then return 'not found' "
                         "else "
                         "local n = length - offset - 4 + 1 "
                         "msg1 = msg:gsub('(Content%-Length%s*:)','%1 '..n.. '') "
                         "return msg1 "
                         "end "

int main(void)
  lua_State *L;
  char *r;

  int length = 0;
  char *msg = "INVITE\r\nContent-Length : \r\n\r\nv=0\r\n";

  L = (lua_State *) luaL_newstate();


  length = strlen(msg);
  lua_pushstring(L, msg);

  r = (char *)luaL_checklstring(L,-1);
  printf("\n\nresult: %s\n\n",r);

  return EXIT_SUCCESS;