stringDatatype:method(...) vs string.method(stringDatatype, ...)

Felt this fit more in #help-and-feedback:code-review rather than #help-and-feedback:scripting-support but if anyone do inform me if I am incorrect. EDIT: Moved to #help-and-feedback:scripting-support

Could not find a post on this topic subject so I have decided to make a thread! If you do find a relevant thread though please reply with it below and I will look at it! (tried searching for “string.method vs string:method” etc.)

Should I use string.method(stringDatatype, ...) or stringDatatype:method(...) where stringDatatype is a variable with the type "string" and string is reference to the string library? I am well aware they do the exact thing in the end, but there feels to be a conflict in consistency when using stringDatatype:method(...)

I am not looking for a “which is more efficient” type answer but rather a “coding style” type answer, specifically one following a pattern that agrees with the Lua 5.1 libraries.

It just feels like stringDatatype:method(...) doesn’t fit with the architecture that other type libraries use; type.method(typeDatatype, ...)

For instance, table. There is no tableDatatype:insert(...) (for obvious reasons probably; conflicts in dictionaries could occur quickly) Another example would be the math library. There is no numberDatatype:sqrt() and so on.

TL;DR: Should I access string library for string functions or access them via the __index metamethod set to the string metatable.

1 Like

To me, the explicit call with string.method(stringDatatype, ...) makes the code more readable and comprehendible–especially if you are doing something rather complex in the adjacent code segments. However, it is a matter of preference. I did search the Lua reference manual, but they really only talk about variable naming conventions and Hungarian notations. I think that since Lua inherently supports parametric / subtype polymorphisms, you should use the string.method call as a matter of type readability and also consistency like you said.

1 Like