arturocepeda / Cflat

Embeddable lightweight scripting language with C++ syntax
49 stars 8 forks source link

Support for dynamic functions like printf, sprintf etc. #8

Closed CycloneRing closed 8 months ago

CycloneRing commented 11 months ago

Hi, is it possible to create functions with dynamic input parameters like printf? Is there a va_list implementation in CFlat? I want to implement a printf in my CFlat script engine.

Thanks

arturocepeda commented 11 months ago

Hi!

Variadic functions are not supported at the moment, but that's something I would like to add at some point, so, knowing that you are interested in that feature, I'll give it a thought and see if I can find a nice way of implementing it.

For the time being, something you could do as a workaround would be to register fixed overloads of printf with all the signatures you need in your scripts. For example, if your use cases are:

  printf("My int value: %d", intVar);
  printf("My 3D vector value: (%.3f, %.3f, %.3f)", vecX, vecY, vecZ);

you can register the two overloads of the function, expecting an int and three floats aside from the format string, respectively:

  CflatRegisterFunctionVoidParams2(env, void, printf, const char*, int);
  CflatRegisterFunctionVoidParams4(env, void, printf, const char*, float, float, float);

Alternatively, you can use cout (in CflatHelper.h you can find the registerStdOut function to register it).

arturocepeda commented 11 months ago

@CycloneRing: after a little investigation, I'm afraid it's not really possible to add generic support for variadic functions the way I would have wished, as the va_list type is not meant to be manipulated directly, but only through the corresponding macros (va_start, va_arg and va_end) - both the definition of the type and the macros, as well as the implementation of their underlying functions, are compiler/platform dependent.

Depending on your use cases, using std::cout or registering the "overloads" of printf you need in your scripts might suffice. But if you really would like to have a full equipped version of printf available for scripting, I guess the only solution would be to add a custom implementation of the function to Cflat.

arturocepeda commented 9 months ago

@CycloneRing: good news! I have found a simple way of providing support for the printf family (concretely snprintf, sprintf and printf). All you have to do is including CflatHelper.h and calling the Cflat::Helper::registerPrintfFamily function once when initializing the environment. I hope this will help!