lua-users home
lua-l archive

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

On Sep 25, 2007, at 12:04 PM, Juri Munkki wrote:

I think you'll find nested tables easier to maintain. You'll have one
extra table for each substitution, but I think that's a fair price for
some added clarity:

replacements = {
	{	"caterpillar", "butterfly" },
	{	"cat", "dog" },
	{	"goldfish", "parrot" }};

function translate(text)
	for i,v in ipairs(replacements) do
		text = text:gsub(v[1], v[2]);

	return text;

print(translate("The cat looked at the caterpillar as if it had just
swallowed a goldfish."));

should print out:

The dog looked at the butterfly as if it had just swallowed a parrot.

Swap the first two lines of the substitutions table to get:

The dog looked at the dogerpillar as if it had just swallowed a parrot.

I just tried that, and in my completely anecdotal tests, this seems to be the fastest solution. And what a great trick - make every replacement a table in itself. But why is this table processed in order? Thanks so much!