lua-users home
lua-l archive

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

I've been playing around with prefixing the scripts I load with startup code. This I've been doing with lua_load() and chunks. I've come across the problem that if I want to flag a specific error in the code that the user wrote I want to be able to tell them in which line number in /their/ code this error occurred on.

Is the only way to do this to scan the characters for \r?\n before they reach lua_load()? Also, if this is the case, is there some means of solving this when loading a pre-compiled lua chunk?

I've put together a minimal example of this behaviour below (the output should indicate an error in line 1, not 3):

Thanks guys,
- Mab

  C++ code
  extern "C" {
      #include "lua.h"
  #include <assert.h>
  #include <stdio.h>
  #include <string.h>

  static int state = STATE_PREFIX;
  static const char* prefix = "-- first line\n-- second line\n";

  enum { BUFFER_SIZE = 128 };
  static const char* filename = "test.lua";
  static FILE* file;
  static char fileBuffer[BUFFER_SIZE];

  static const char* ChunkReader(
      lua_State*  L,
      void*       data,
      size_t*     size)
      if (state == STATE_PREFIX) {
          *size = strlen(prefix);
          state = STATE_FILE;
          return prefix;
      } else if (state == STATE_FILE) {
          *size = fread(fileBuffer, 1, BUFFER_SIZE, file);
          return *size ? fileBuffer : 0;

      return 0;

  int main()
      file = fopen(filename, "rt");

      lua_State* L = lua_open();
      lua_load(L, ChunkReader, 0, filename);
      assert(lua_gettop(L) == 1);
      assert(lua_type(L, 1) == LUA_TSTRING);
      printf("%s", lua_tostring(L, 1));


      return 0;

  1 = i	-- obviously an error

  [string "test.lua"]:3: unexpected symbol near `1'