| 754 | |
| 755 | |
| 756 | static int str_format (lua_State *L) { |
| 757 | int arg = 1; |
| 758 | size_t sfl; |
| 759 | const char *strfrmt = luaL_checklstring(L, arg, &sfl); |
| 760 | const char *strfrmt_end = strfrmt+sfl; |
| 761 | luaL_Buffer b; |
| 762 | luaL_buffinit(L, &b); |
| 763 | while (strfrmt < strfrmt_end) { |
| 764 | if (*strfrmt != L_ESC) |
| 765 | luaL_addchar(&b, *strfrmt++); |
| 766 | else if (*++strfrmt == L_ESC) |
| 767 | luaL_addchar(&b, *strfrmt++); /* %% */ |
| 768 | else { /* format item */ |
| 769 | char form[MAX_FORMAT]; /* to store the format (`%...') */ |
| 770 | char buff[MAX_ITEM]; /* to store the formatted item */ |
| 771 | arg++; |
| 772 | strfrmt = scanformat(L, strfrmt, form); |
| 773 | switch (*strfrmt++) { |
| 774 | case 'c': { |
| 775 | sprintf(buff, form, (int)luaL_checknumber(L, arg)); |
| 776 | break; |
| 777 | } |
| 778 | case 'd': case 'i': { |
| 779 | addintlen(form); |
| 780 | sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); |
| 781 | break; |
| 782 | } |
| 783 | case 'o': case 'u': case 'x': case 'X': { |
| 784 | addintlen(form); |
| 785 | sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); |
| 786 | break; |
| 787 | } |
| 788 | case 'e': case 'E': case 'f': |
| 789 | case 'g': case 'G': { |
| 790 | sprintf(buff, form, (double)luaL_checknumber(L, arg)); |
| 791 | break; |
| 792 | } |
| 793 | case 'q': { |
| 794 | addquoted(L, &b, arg); |
| 795 | continue; /* skip the 'addsize' at the end */ |
| 796 | } |
| 797 | case 's': { |
| 798 | size_t l; |
| 799 | const char *s = luaL_checklstring(L, arg, &l); |
| 800 | if (!strchr(form, '.') && l >= 100) { |
| 801 | /* no precision and string is too long to be formatted; |
| 802 | keep original string */ |
| 803 | lua_pushvalue(L, arg); |
| 804 | luaL_addvalue(&b); |
| 805 | continue; /* skip the `addsize' at the end */ |
| 806 | } |
| 807 | else { |
| 808 | sprintf(buff, form, s); |
| 809 | break; |
| 810 | } |
| 811 | } |
| 812 | default: { /* also treat cases `pnLlh' */ |
| 813 | return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " |
nothing calls this directly
no test coverage detected