3 ms·
String trim is just: foo:gsub("%s*$", "") or foo:gsub("^%s*", "") The standard idiom for OOP in Lua is a one-liner: return setmetatable(self, mt) wh
by wahern 10y ago
String trim is just:
foo:gsub("%s*$", "")
or
foo:gsub("^%s*", "")
The standard idiom for OOP in Lua is a one-liner:
return setmetatable(self, mt)
where mt.__index has all the methods. How you assign to mt.__index can vary across modules according to style, but that's a _purely_ asethetic issue. The mechanics are identical. Using a module to accomplish it creates a useless dependency.
There are many criticisms one could make of Lua, but I don't think those two particular criticisms are legit. They're classic bikeshedding.
- JoshTriplett 10y agoIf you're reading a pile of string processing code, seeing s.rstrip() helps make code self-documenting, compared to s:gsub("%s*$", "") I don't want to argue for a massive standard library (for instance, I don't think Python should have shipped modules for dbm, bdb, sqlite, or XML-RPC), but simple string processing seems like a good thing to standardize.
- brandonbloom 10y agoString processing is never simple. Simply identifying "what is whitespace?" is a big undertaking in Unicode. Lua's philosophy seems to be to include the absolute minimum that is unacceptably painful to omit. This is a perfectly reasonable tradeoff for Lua's primary use case: embedding. With respect to strings in particular, most systems that Lua is embedded in has its own string type, or inherits one from a framework. This is an unfortunate reality of the C/C++ world. Returning to my point about language standard libraries: The lack of a traditional "standard library" is a feature for Lua, but only because Lua has a strong FFI and C API that acts as a "bring your own standard library" mechanism. It's less about needing a standard library, and more about admitting a language is only one piece of the puzzle. For a language to flourish, you need to have some story for interfacing with the rest of the world in a rich way.
- ufo 10y agoThe function you presented that trims to the right has quadratic runtime behavior if your string has a long sequence of spaces that is not at the end of the string. For example, "a b". A similar performance bug was behind a 30 minute downtime at stackoverflow.com, because a code snippet with 20 thousand spaces inside a comment showed up on their frontpage. See, its not that simple :) http://lua-users.org/wiki/StringTrim http://lua-users.org/wiki/StringTrim Anyway, I wasn't trying to say bad things about Lua with my examples. Its just that if you go to any large Lua project out there there is a very good chance you will find some "utils" module in there with yet another reimplementation of a lot of these common functions. Ideally we should have people reusing more stuff from Luarocks than they are right now.