Amaroq7 / SPMod

SourcePawn Scripting Engine for Half-Life 1 based games
GNU General Public License v3.0
27 stars 12 forks source link

Python-like format syntax #18

Open WPMGPRoSToTeMa opened 6 years ago

WPMGPRoSToTeMa commented 6 years ago

Examples:

Format("Hello, {:s}!", "world"); // "Hello, world"
Format("{0:s}{1:s}{0:s}", "abra", "cad"); // "abracadabra"
Format("The answer is {:d}.", 42); // "42"
Format("Hello, {name:s}! The answer is {number:d}. Goodbye, {name:s}.", FmtArg("name", "World"), FmtArg("number", 42)); // "Hello, World! The answer is 42. Goodbye, World."

There is tagof operator in SP, can we use it for type auto-examination? Can we use it at least for FmtArg? If not, should we add argument in FmtArg to pass the type?

Also we can choose default type for {}, but there are several frequently used types, so I don't prefer it.

Amaroq7 commented 6 years ago

This looks handy. I think we could we use fmtlib for this kind of formatting. Could you provide some example how would you like to use tagof operator?

WPMGPRoSToTeMa commented 6 years ago

Something like this:

#define A(%0) FmtArg(#%0, tagof(%0), %0)

stock SomePackedType FmtArg(const char[] name, int tag, any ...) {
  int intVar;
  float floatVar;
  char charVar;
#pragma unused intVar
#pragma unused floatVar
#pragma unused charVar

  EnumOfTypes type;
  switch (tag) {
    case tagof(intVar): type = Type_Int;
    case tagof(floatVar): type = Type_Float;
    case tagof(charVar): type = Type_String;
  }

  return /*packed name, type and variable value*/;
}

Usage example:

Format("You hit {victimName} ({victimHealth} hp) with {damage} damage", A(victimName), A(victimHealth), A(damage));

Idk how to check if variable is an array. Unfortunately sizeof can't help here (it gives a compile-time error for unsized arrays).

What about fmtlib, idk how it can help us, because we can't just extract parsing code from it.