0

Many times I need to have a variable to express the type of something, but as you probably know it is also the name of a function in Lua.

What could be a proper workaround? I thought of:

  1. Use it anyways. Since I use almost only local values, the type function isn't overwritten but it becomes temporarily inaccessible (also a problem when used as an argument name).
  2. Using a synonym of the word "type" (probably the easiest solution), but I can't come up with anything good.
  3. Using upper case, prefix/suffix, like Type, TYPE or _type, but it goes against the code style used so far.
  4. Save the type function as something else and restore it at the end.
  5. Add a global reference to type called for example 'typeof' so that when type is used locally I can still use typeof.
  6. Recompile Lua with a different name for the type function (no thanks!)
2
  • That's hardly a question, you've already listed options, pros and cons, and it's up to you to choose the one that better fits your needs. As for first option - i'll add that it's error-prone, some day you'll forget local. typeof may be a good name for builtin because it's widely known in other languages, but experienced lua-scripters may find it unexpected - that really depends on who will write this scripts.
    – keltar
    Oct 10, 2013 at 6:27
  • You are not looking for alternatives of type. You are making a new function that uses the name type, it's opinion-based how to solve the problems but my suggestion is simply give your function another name.
    – Yu Hao
    Oct 10, 2013 at 7:23

2 Answers 2

2

The only sensible options are #2 and #3, choosing one of the others usually is asking for troubles.

Keep in mind that naming conventions are just that, conventions. In exceptional cases breaking the convention to make the code more readable is a good thing.

On the other hand, overloading/changing/fiddling with the standard library names is far worse, especially because you do it just to avoid some names that you don't like so much for your identifiers.

Although they are not considered reserved identifiers with the same strong rules as C (the only really reserved names are those that begins with an underscore followed by a capital letter), Lua standard library names should be considered reserved, unless you have an extremely compelling reason to do otherwise, especially in large applications. Preserving naming conventions is not such a compelling reason.

1

Usually I use the word kind for that purpose.

1
  • I see, thank you. I'm so used at using "type" that thinking of another word feels somewhat strange.. guess I have to get used to it. Oct 10, 2013 at 17:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.