Get Class From String?

If I have a class defined with the string "Player" like so:

class('Player').extends()

Am I able to get a reference to that class later from the string "Player"?

I am reading level data in from a file and was hoping that it would be easy to read in an entity in that file with a name like "Player" and easily instantiate that object with Player(), but I am not seeing anyway to get from a string to the object class once it has been declared. Does that just not exist?

I can do something silly like:

function getClassFromString(s)
 if s == "Player" then return Player end
end

...

-- elsewhere, in the main file
local class = getClassFromString("Player")
local player = class()

That seems to work. But then I'd need to update this function for every single kind of Class that I could potentially be reading in from the file, which seems like a pain. Is there really no way to go from the string name of the class to the class itself that I am missing?

A more barebones option could be to get the class by name from the global _ENV table, so your factory function could return _ENV[s] with any suitable sanity checks you might need. You could augment this with a registry of types to limit the ones that the factory is allowed to handle, then use that. The factory could also accept variadic arguments and use those to create and return an instance of the class in question instead of the class, depending on your needs. Is this closer to what you had in mind?

1 Like

Woah, that _ENV[s] trick is basically exactly what I was looking for. Thanks!

I guess I should look more into what the global _ENV table is; I'd not heard of that before posting this here.

2 Likes