tags:

views:

145

answers:

2

I have a global variable:

const double myvar = 5.1;

Now, I'm converting this to read these values from Lua.

However, I can't simply do:

const double myvar = lua_tonumber(L,1);

Since main() must first execute to start the Lua intepreter etc., but if I declare myvar afterwards, it will not be global.

Is there any way to do achieve a global const variable which takes it's value from Lua?

A: 

You can violate constness like this:

*(double*) & myvar = lua_tonumber(L,1);

but it's a -very- bad practice.

Edit: Instead of declaring const variables you can do this:

static double myvar() {
 // todo: check if global L is init
 return lua_tonumber(L,1);
}

or even this:

static double myvar() {
 return 1.15;
}
Nick D
Thanks. This causes a crash when myvar is declared as const to begin with.
See my edit .
Nick D
+5  A: 

The subtle ramifications of const can be fully understood only by language lawyers, but the basic idea of a const variable is that its value is specified at compile time. Lua values cannot be created until there is a Lua interpreter, which requires calling lua_open(), which cannot be done until run time. So no, there is no (safe, sane) way of having a const variable whose value is determined by Lua.

Norman Ramsey