Lua StringBuilder OO Concept #614
Replies: 3 comments 1 reply
-
You could also do this: :) function self.linebreaker(char,length) local char = char or "" return string.rep(char,length).."\n" end |
Beta Was this translation helpful? Give feedback.
-
I think the parameter … so in the constructor, you would just need: function StringBuilder:new(firstString) self._firstString = firstString or "" setmetatable({}, self) self.__index = self --- @type string private field holding the official string value self.value = self._firstString --- @type boolean flag to enable exception raised if a value other than string/number/boolean/integer attempted do --[[ core functions --]] --- return length of the StringBuilder --- @return integer length currenty length of the StringBuilder self.length = function() return #self.value end self.typeCast = function(value) local t = type(value) --[[ There are eight basic types in Lua: nil, boolean, number, string, userdata, function, thread, and table. The type function gives the type name of a given value: print(type("Hello world")) --> string print(type(10.4*3)) --> number print(type(print)) --> function print(type(type)) --> function print(type(true)) --> boolean print(type(nil)) --> nil print(type(type(X))) --> string ]] local isNotTypeSafe = true if t == "string" or t == "number" or t == "boolean" or t == "integer" then isNotTypeSafe = false end if isNotTypeSafe then -- throw error local msg = string.format( "StringTyping is enabled and value passed is not Type-Safe(string/number/boolean):[%s]", t ) error(msg, -1) -- throw error end return tostring(value) -- tostring coverts boolean to string false/true -- otherwise let tostring() come up with whatever it wants end end return self end 😊 |
Beta Was this translation helpful? Give feedback.
-
Thank you! All those posts I made my back, it was usually a case of me learning as I wrote. So, a lot of it I would probably change now. But, it’s really the best way to learn something more deeply. 🙏 |
Beta Was this translation helpful? Give feedback.
-
StringBuilder OO Concept
been missing my StringBuilders from C# & Java, so rolling my own Lua one
Beta Was this translation helpful? Give feedback.
All reactions