luaL_openlibs(L) Linking problems

Started by
7 comments, last by link3333 15 years, 6 months ago
I've downloaded and installed lua version 5.1.4.18 from the lua.org site. I'm running Visual Studio C++ 2008 and have included the lib's and includes at tools->options->projects and solutions->VC++ Directories and added lua5.1.lib and lua51.lib for the projects linker input dependencies and I still get a bunch of unresolved external symbol errors on the following code:

#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main (void) {
  char buff[256];
  int error;
  lua_State *L = lua_open();   /* opens Lua */
  luaL_openlibs(L);

  while (fgets(buff, sizeof(buff), stdin) != NULL) {
    error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
            lua_pcall(L, 0, 0, 0);
    if (error) {
      fprintf(stderr, "%s", lua_tostring(L, -1));
      lua_pop(L, 1);
    }
  }

  lua_close(L);
  return 0;
}

Advertisement
It may be because you are including the raw C header files. Try including "lua.hpp" instead, this will add a extern "C" { } to your includes, and should solve a few problems.

[size=1]Visit my website, rawrrawr.com

Hey, thanks heaps, compiles perfectly :) Can you explain why that worked please?
C++ and C, while very similar, are actually different languages. C++ uses a technique called name mangling to generate function names (hidden from the coder), while C dosn't do anything of the sort.

Since you were loading a C .lib file, with C code from a C++ project without using extern "C", the compiler assumed that your code was in C++, and mangled your names for you. This made it impossible to find the newly mangled names in the library file, resulting in unresolved externals.

Normally, you would solve this by putting extern "C" around the stuff that you knew was in C. However, since lua is by itself, a C library, they didn't do that. What they did do, was provide lua.hpp, which just puts extern "C" around their own header files for you, suppressing the name mangling and making the linker all happy again.

[size=1]Visit my website, rawrrawr.com

So what would I have to do if I wanted to change it too C++ code?
A lot of work; lua is a C library. The use of the lua.hpp header works perfectly fine, there isn't really any reason to change lua to a C++ library at all.

[size=1]Visit my website, rawrrawr.com

Ahh ok, fair enough, thanks for your help.
Ok, new question, say I have a lua script like this:

number = 1
print(number)

how do I execute this file from my C++ code?
In C++, call luaL_dofile. It's a macro that calls functions to load and immediately run the given script.

This topic is closed to new replies.

Advertisement