Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a percentage sign in Lua string.format

Tags:

lua

In a modification script I'm developing for an online game, I'm attempting to display the current percentage of a number.

function()
    local z = math.max(0, UnitPower("player")) / math.max(1, UnitPowerMax("player")) * 100;
    return string.format("%.f", z);
end

The code above displays the percentage correctly.

However, I am having a difficult time getting the actual percentage sign to show up without throwing errors everywhere.

I've tried adding print("%%") before ending the function as well as after the function, but it doesn't seem to work.


2 Answers

The function string.format, like printf in C, requires the percent sign to be doubled when you want it verbatim. This is not the case for print or io.write functions !

So you certainly want this :

function()
  local z = math.max(0, UnitPower("player")) / math.max(1, UnitPowerMax("player")) * 100;
  return string.format("%.f %%", z);
end
like image 104
prapin Avatar answered Apr 20 '26 21:04

prapin


Figured it out.

function()
    local z = math.max(0, UnitPower("player")) / math.max(1, UnitPowerMax("player")) * 100;
    return string.format("%.f", z) .. "%%";
end

Just added .. "%%"; the value shown is now 100% (where 100 is the current percentage.

Super late edit:
This was part of some custom code being entered into an addon for the video game World of Warcraft, and this is the solution for the goal I wanted to achieve because the author was calling string.format() around the "custom code" input. Refer to the other answer on this question for the standard Lua solution.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!