如何在Lua中编写星号图案程序?解决代码单行打印问题
Hey there! Let's sort out your Lua asterisk pattern issue and walk through how to build these patterns properly.
First: Fixing Your Existing Code
Your current code is printing each asterisk on a new line because Lua's print() function automatically adds a newline after every call. That's why all your * are stacked vertically instead of forming rows. Here are two simple fixes:
Fix 1: Build a string for each line first
Instead of printing each asterisk individually, we'll build a complete line of asterisks as a string, then print the whole line at once:
for i = 6, 1, -1 do local line = "" -- Initialize an empty string for the current line for j = 1, i do line = line .. "*" -- Append each asterisk to the line string end print(line) -- Print the full line end
Fix 2: Use io.write() (no automatic newline)
io.write() outputs text without adding a newline automatically, so we can manually add a newline at the end of each row:
for i = 6, 1, -1 do for j = 1, i do io.write("*") -- Print asterisks without newlines end io.write("\n") -- Manually add a newline after the row end
Both of these will output the inverted triangle you're aiming for:
****** ***** **** *** ** *
Next: Writing Other Asterisk Patterns in Lua
Once you get the hang of the core logic (outer loop for rows, inner loops for characters per row), you can create all sorts of patterns. Here are a few common examples:
1. Regular Triangle (Increasing Asterisks)
-- Prints a triangle that grows from 1 to 6 asterisks per row for i = 1, 6 do local line = "" for j = 1, i do line = line .. "*" end print(line) end
Output:
* ** *** **** ***** ******
2. Pyramid Pattern
This one adds leading spaces to center the asterisks:
local total_rows = 6 for i = 1, total_rows do -- Print leading spaces for j = 1, total_rows - i do io.write(" ") end -- Print asterisks (2*i -1 gives odd numbers for symmetry) for j = 1, 2*i - 1 do io.write("*") end io.write("\n") end
Output:
* *** ***** ******* ********* ***********
Key Takeaways
- Outer loop: Controls the number of rows in your pattern.
- Inner loops: Handle the number of characters (asterisks or spaces) per row.
- Output control: Use either string concatenation +
print()orio.write()with manual newlines to avoid unwanted line breaks.
内容的提问来源于stack exchange,提问作者Abhishek Singh

