Page 1 of 1

retrieving a word-wrapped string

Posted: Mon Aug 03, 2015 5:05 am
by decky
hello,

i desire a function that, given a string, a width constraint, and a Font, returns a copy of the string with word wrapping applied. although Font:getWrap helpfully returns the number of lines that the text was wrapped to, it does not return the wrapped text itself. do you have a solution?

i have already accomplished this by modifying the source code for the getWrap function like so:

Code: Select all

/*modules/graphics/opengl/wrap_Font.cpp*/

int w_Font_getWrap(lua_State *L)
{
	Font *t = luax_checkfont(L, 1);
	const char *str = luaL_checkstring(L, 2);
	float wrap = (float) luaL_checknumber(L, 3);
	int max_width = 0, numlines = 0;
	std::vector<std::string> lines;

	luax_catchexcept(L, [&]() {
		lines = t->getWrap(str, wrap, &max_width);
		numlines = lines.size();
	});

	// return max width and number of lines
	lua_pushinteger(L, max_width);
	lua_pushinteger(L, numlines);

	// my addition: return a list of the lines
	lua_newtable(L);
	for (int i = 0; i<numlines; i++){
		lua_pushinteger(L, i+1);
		lua_pushstring(L, lines[i].c_str());
		lua_settable(L, -3);
	}

	return 3;
}

Code: Select all

myFont = love.graphics.newFont(18)
width, numLines, lines = myFont:getWrap("The quick brown fox jumps over the lazy dog.", 200)

print(lines[1]) # The quick brown fox
however, i don't consider maintaining my own fork of LÖVE to be an ideal solution, so i'd appreciate any alternatives.

for your curiosity: my main purpose for this is to create text boxes that have vertical margins and hide any lines of text that would flow beyond the margins.

Re: retrieving a word-wrapped string

Posted: Mon Aug 03, 2015 9:14 am
by Nixola
You'll either have to wait for 0.10.0 or, as you did, do it yourself. Before editing LÖVE's code, though, see if you can make it work via LuaJIT's FFI module.

Re: retrieving a word-wrapped string

Posted: Mon Aug 03, 2015 6:19 pm
by decky
thanks for the reply. so this functionality is planned for 0.10? that's good to know...

i haven't used luajit's FFI library before, but doesn't it only work with c? if i have to declare every type and function that i use, then i can't work with Fonts, because Font is a c++ class and i can't declare it as a c struct.