Modifying strings returned by luaL_checkstring()?

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Modifying strings returned by luaL_checkstring()?

Marc Balmer
Is it allowed to modify strings returned by lua_tolstring, luaL_checkstring etc.? (after casting to a char *).

Or does that have any negative side effects?

- mb


Reply | Threaded
Open this post in threaded view
|

Re: Modifying strings returned by luaL_checkstring()?

Andrew Gierth
>>>>> "Marc" == Marc Balmer <[hidden email]> writes:

 Marc> Is it allowed to modify strings returned by lua_tolstring,
 Marc> luaL_checkstring etc.? (after casting to a char *).

Absolutely not.

 Marc> Or does that have any negative side effects?

It breaks everything.

--
Andrew.

Reply | Threaded
Open this post in threaded view
|

Re: Modifying strings returned by luaL_checkstring()?

Gé Weijers
In reply to this post by Marc Balmer

On Sun, Apr 7, 2019 at 3:17 AM Marc Balmer <[hidden email]> wrote:
Is it allowed to modify strings returned by lua_tolstring, luaL_checkstring etc.? (after casting to a char *).

Or does that have any negative side effects?

Lua stores only one copy of each string if it's below a certain length, this speeds up lookups when using strings as table indices tremendously, and saves some space too. So if you change the contents of the string you may see some very strange side effects, like "foo" and "foo" being unequal strings.

You really should use a userdata object as a scratch buffer in C routines, for two reasons:
  • the Lua interpreter does not care about the contents, so you can use it for anything.
  • if you call a Lua C API function that produces an error which terminates your function the function's stack frame is discarded and the userdata memory is freed eventually. If you use malloc/free that won't happen unless you use lua_pcall/lua to catch the error and explicitly free the memory in your code.


--
--

Reply | Threaded
Open this post in threaded view
|

Re: Modifying strings returned by luaL_checkstring()?

Eric Westbrook
On 2019-04-08 10:33, Gé Weijers wrote:
> On Sun, Apr 7, 2019 at 3:17 AM Marc Balmer <[hidden email]> wrote:
>
> You really should use a userdata object as a scratch buffer in C
> routines, for two reasons:
>

I've also found the use of a luaL_Buffer very useful for this purpose,
with similar if not identical advantages, when the "scratch data"
consists of strings rather than general purpose C data types.

US$0.02,
Eric Westbrook