lua-users home
lua-l archive

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


(sorry if I spam the list a bit with my questions)

My goal:  Create a modifiable copy of a string in a C module, so that the copy of the string can be used with the strtok_r() function (which modifies the string passed as first argument).

So far I came up with two different ways:

First variant:

	const char *s;
	char *u;

	s = luaL_checklstring(L, 2, &len);
	u = lua_newuserdata(L, len);
	memcpy(u, s, len);

Here I use 'u' as the first argument to the strtok_r() call.

Second variant:

	char *s;

	s = (char *)lua_pushfstring(L, "%s,", luaL_checkstring(L, 2));

Not that I add a command in the format string, to make the strings not similar, which apparently causes Lua to create a new string and not reuse the original string data.  The comma is part of the delimiter argument to strtok_r(), so it does not affect my code.

Are both variants valid?

fwiw, I am using strtok_r to tokenize a a string passed to a function, and then use luaL_checkoption() to get the individual values for each token, or'ing them together to a flag value. The following C code

p = dlopen('whatever', RTLD_LAZY | RTLD_GLOBAL)

becomes the following Lua code

local p = dlopen('whatever', 'lazy, global')