Rolf Wester
Rolf Wester

Reputation: 217

Julia macros: @__FILE__ @__LINE__ in macro

This code:

macro FL(message) 
    return @sprintf("%s:%d | %s", @__FILE__, @__LINE__, message) # line 2
end
println(@FL("m")) # line 4

prints fl.jl:2 | m. How can I make it print fl.jl:4 | m?

Upvotes: 6

Views: 785

Answers (2)

Isaiah Norton
Isaiah Norton

Reputation: 4366

The following will work in the current Julia nightly:

macro FL(message) 
    return :(@sprintf("%s:%d | %s", $(string(__source__.file)), $(__source__.line), $(esc(message)))) # line 2
end
println(@FL("m")) # line 4

This was made possible by the following implementation pull request. It is not possible in any officially released version, unfortunately.

Upvotes: 5

houtanb
houtanb

Reputation: 4100

Though there may be more elegant ways to do this, if you don't want this to block your progress on other fronts, why not just pass the line number to the macro...

macro FL(message, line)
    return @sprintf("%s:%d | %s", @__FILE__, line, message)
end
println(@FL("m", @__LINE__))

Upvotes: 3

Related Questions