John
John

Reputation: 2363

Stringify object name in Lua

In C I can do following:

#define S1(x) #x
#define S(x) S1(x)
#define foo(x) bar(x, S(x))

int obj = 3;
foo(obj);

void bar(int v, const char * name)
{
    // v == 3
    // name == "obj" 
}

Can I do the same in Lua?

foo(barbar)

function foo(ob)
  -- can I get "barbar"?
end

Upvotes: 2

Views: 3013

Answers (3)

jpjacobs
jpjacobs

Reputation: 9549

You Could do this, but as DeadMG suggested: don't.

A way would be:

function foo(bar)
    return bar
end

print(foo(bar)) -- prints nil

setmetatable(_G,{__index=function(t,k)
    if k:match"^_" then -- Don't use on system variables
        return nil
    else
        return k
    end
end})

print(foo(bar)) -- prints bar

But I would strongly comment against it, as this can have nasty side effects.

Upvotes: 2

Puppy
Puppy

Reputation: 146968

No, I don't believe you can. The use of such is dubious to begin with.

Upvotes: 0

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74790

I think you could do something similar only by using a preprocessor which does something similar to your C preprocessor code. (The plain C compiler can't do something like that, too.)

Or write it explicitly:

foo(barbar, "barbar")

Upvotes: 2

Related Questions