Search code examples
delphifpc

convert string to set type


In my application I have many sets defined:

eBlockTypes = (btNone,btUndefined,btStone, btYellowFlower, btWoodBrown...);

sMinerals = set of eBlockTypes; 

var
  mineralsRare: sMinerals;
  mineralsPlants: sMinerals;
  mineralsAll: sMinerals;
  mineralsDeep: sMinerals;
  mineralsWalkable: sMinerals;
  mineralsDiggable: sMinerals; 

then I have an object that has 'sMinerals' as one of it's fields. Is it possible to read set's 'name' when loading object properties from file?

edit: more details. Let's say that object definition in file looks like that:

[item]
Computer
[requires]
3 Circuit board
1 Medium CPU
3 Plastic
[placement]
mineralsWalkable

so I can parse the file and read all the properties besides the set 'mineralsWalkable'. I know that I could compare that string with some TStrings holding all the sets names but the quiestion is: is it possible get that set by converting the string to variable somehow?


Solution

  • What you can read from a file depends on what's in the file. If you wrote the names of your variables into the file, then you should be able to read them, too. If not, then you can't. Variables names are not inherently written to files when you wrote data, though.

    Identify the technique used to write the names into your file. To read them, simply perform the inverse operation. If you wrote the data delimited in some way, then read until you encounter a delimiter. If you preceded the name with its character length, then read the length, and then read that many characters. If you didn't write the names with a technique that's invertible, then you'll have to change how you write your data before proceed to reading it.

    Your question asked whether it was possible to read the names, and the answer is yes. You've since asked another question, which is whether it's possible to "convert" the name read from the file into the actual variable with the corresponding name. The answer to that is no.

    Ordinary variables do not have RTTI; Delphi does not maintain the names of all the variables in a program. Once the compiler finishes its job, the names cease to exist within the program.

    The easiest way to get the variable is to set up a mapping from string to set value. Read the name from the file, look up the name in a data structure, and use the corresponding value. A TDictionary<string, sMinerals> would be perfect for that. Just populate the data structure as your program starts up.